'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Link as LinkIcon, Shield, Clock, Download, Check, Copy } from 'lucide-react';
import api from '@/lib/api';

interface ShareModalProps {
  filePath: string;
  onClose: () => void;
}

export default function ShareModal({ filePath, onClose }: ShareModalProps) {
  const [password, setPassword] = useState('');
  const [expiresIn, setExpiresIn] = useState(''); // hours
  const [maxDownloads, setMaxDownloads] = useState('');
  const [loading, setLoading] = useState(false);
  const [shareLink, setShareLink] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleCreate() {
    setLoading(true);
    setError(null);
    try {
      const exp = parseInt(expiresIn, 10);
      const dl = parseInt(maxDownloads, 10);
      const res = await api.createShare(
        filePath,
        password || undefined,
        isNaN(exp) ? undefined : exp,
        isNaN(dl) ? undefined : dl
      );
      
      const fullUrl = `${window.location.origin}${res.link}`;
      setShareLink(fullUrl);
    } catch (err: any) {
      setError(err.message || 'Failed to create share link');
    } finally {
      setLoading(false);
    }
  }

  function handleCopy() {
    if (!shareLink) return;
    navigator.clipboard.writeText(shareLink);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" onClick={onClose}>
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        exit={{ opacity: 0, scale: 0.95 }}
        onClick={(e) => e.stopPropagation()}
        className="w-full max-w-md rounded-2xl overflow-hidden flex flex-col"
        style={{ backgroundColor: 'var(--color-bg-primary)', border: '1px solid var(--color-border)' }}
      >
        <div className="flex items-center justify-between p-4 border-b" style={{ borderColor: 'var(--color-border-subtle)' }}>
          <h2 className="text-lg font-semibold" style={{ color: 'var(--color-text-primary)' }}>Share File</h2>
          <button onClick={onClose} className="p-1 rounded-lg hover:bg-white/5 transition-colors">
            <X className="w-5 h-5" style={{ color: 'var(--color-text-tertiary)' }} />
          </button>
        </div>

        <div className="p-5 space-y-5">
          <p className="text-sm truncate" style={{ color: 'var(--color-text-secondary)' }}>
            Creating public link for <strong>{filePath.split('/').pop()}</strong>
          </p>

          {error && (
            <div className="p-3 rounded-lg text-sm" style={{ backgroundColor: 'rgba(239, 68, 68, 0.1)', color: 'var(--color-danger)' }}>
              {error}
            </div>
          )}

          {!shareLink ? (
            <>
              {/* Configuration */}
              <div className="space-y-4">
                <div>
                  <label className="flex items-center gap-2 text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-primary)' }}>
                    <Shield className="w-4 h-4" /> Password (Optional)
                  </label>
                  <input
                    type="text"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="Leave blank for no password"
                    className="w-full px-3 py-2 rounded-lg text-sm outline-none"
                    style={{ backgroundColor: 'var(--color-bg-tertiary)', border: '1px solid var(--color-border)', color: 'var(--color-text-primary)' }}
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="flex items-center gap-2 text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-primary)' }}>
                      <Clock className="w-4 h-4" /> Expires In (Hours)
                    </label>
                    <input
                      type="number"
                      min="1"
                      value={expiresIn}
                      onChange={(e) => setExpiresIn(e.target.value)}
                      placeholder="Never"
                      className="w-full px-3 py-2 rounded-lg text-sm outline-none"
                      style={{ backgroundColor: 'var(--color-bg-tertiary)', border: '1px solid var(--color-border)', color: 'var(--color-text-primary)' }}
                    />
                  </div>
                  <div>
                    <label className="flex items-center gap-2 text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-primary)' }}>
                      <Download className="w-4 h-4" /> Max Downloads
                    </label>
                    <input
                      type="number"
                      min="1"
                      value={maxDownloads}
                      onChange={(e) => setMaxDownloads(e.target.value)}
                      placeholder="Unlimited"
                      className="w-full px-3 py-2 rounded-lg text-sm outline-none"
                      style={{ backgroundColor: 'var(--color-bg-tertiary)', border: '1px solid var(--color-border)', color: 'var(--color-text-primary)' }}
                    />
                  </div>
                </div>
              </div>

              <button
                onClick={handleCreate}
                disabled={loading}
                className="w-full py-2.5 rounded-xl text-sm font-medium text-white transition-opacity hover:opacity-90 disabled:opacity-50 mt-2"
                style={{ background: 'linear-gradient(135deg, var(--color-accent), #8b5cf6)' }}
              >
                {loading ? 'Creating...' : 'Create Link'}
              </button>
            </>
          ) : (
            <>
              {/* Success View */}
              <div className="flex flex-col items-center justify-center py-4">
                <div className="w-12 h-12 rounded-full flex items-center justify-center mb-3" style={{ backgroundColor: 'rgba(34, 197, 94, 0.1)' }}>
                  <Check className="w-6 h-6" style={{ color: 'var(--color-success)' }} />
                </div>
                <p className="text-sm font-medium text-center mb-4" style={{ color: 'var(--color-text-primary)' }}>
                  Share link created successfully!
                </p>

                <div className="w-full flex items-center gap-2 p-1 rounded-lg" style={{ backgroundColor: 'var(--color-bg-tertiary)', border: '1px solid var(--color-border)' }}>
                  <input
                    type="text"
                    readOnly
                    value={shareLink}
                    className="flex-1 bg-transparent px-2 py-1 text-sm outline-none"
                    style={{ color: 'var(--color-text-primary)' }}
                  />
                  <button
                    onClick={handleCopy}
                    className="flex items-center gap-1 px-3 py-1.5 rounded text-xs font-medium transition-colors"
                    style={{ backgroundColor: 'var(--color-accent)', color: 'white' }}
                  >
                    {copied ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
                    {copied ? 'Copied' : 'Copy'}
                  </button>
                </div>
              </div>
            </>
          )}
        </div>
      </motion.div>
    </div>
  );
}
