'use client';

import { useState, useEffect } from 'react';
import { Shield, CheckCircle2, AlertTriangle, ArrowRight, Upload, FileText, Clock, XCircle } from 'lucide-react';
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { authService } from '@/services/auth.service';
import { getErrorMessage } from '@/lib/errors';
import { useSystemConfig } from '@/hooks/useSystemConfig';

interface VerificationData {
  adminMessage: string | null;
  isVerificationEnabled: boolean;
  currentStatus: string | null;
  documentUrl: string | null;
}

export default function VerificationPage() {
  const sysConfig = useSystemConfig();
  const [loading, setLoading] = useState(false);
  const [pageLoading, setPageLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const [verificationData, setVerificationData] = useState<VerificationData | null>(null);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [dragActive, setDragActive] = useState(false);

  const ACCEPTED_TYPES = ['image/jpeg', 'image/png', 'application/pdf'];
  const MAX_BYTES = sysConfig.verificationMaxSizeMb * 1024 * 1024;
  const acceptFile = (file: File): string | null => {
    if (!ACCEPTED_TYPES.includes(file.type)) return 'Only JPEG, PNG, and PDF files are allowed';
    if (file.size > MAX_BYTES) return `File must be under ${sysConfig.verificationMaxSizeMb}MB`;
    return null;
  };

  useEffect(() => {
    loadVerificationData();
  }, []);

  const loadVerificationData = async () => {
    try {
      const response = await fetch('/api/verification/page-data', {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`,
        },
      });
      if (response.ok) {
        const data = await response.json();
        setVerificationData(data);
        if (data.currentStatus === 'VERIFIED') {
          setSuccess(true);
        }
      }
    } catch (err) {
      console.error('Failed to load verification data:', err);
    } finally {
      setPageLoading(false);
    }
  };

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true);
    } else if (e.type === 'dragleave') {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      const file = e.dataTransfer.files[0];
      const err = acceptFile(file);
      if (err) setError(err);
      else { setSelectedFile(file); setError(null); }
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0];
      const err = acceptFile(file);
      if (err) setError(err);
      else { setSelectedFile(file); setError(null); }
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedFile) {
      setError('Please select a document to upload');
      return;
    }

    setError(null);
    setLoading(true);

    try {
      const formData = new FormData();
      formData.append('document', selectedFile);

      const response = await fetch('/api/verification/upload', {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`,
        },
        body: formData,
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.message || 'Upload failed');
      }

      setSuccess(true);
      setSelectedFile(null);
      await loadVerificationData();
    } catch (err) {
      setError(getErrorMessage(err));
    } finally {
      setLoading(false);
    }
  };

  const getStatusDisplay = () => {
    switch (verificationData?.currentStatus) {
      case 'PENDING':
        return {
          icon: <Clock className="h-5 w-5 text-amber-500" />,
          title: 'Verification Pending',
          message: 'Your document has been uploaded and is awaiting review by our team.',
          color: 'amber',
        };
      case 'VERIFIED':
        return {
          icon: <CheckCircle2 className="h-5 w-5 text-emerald-500" />,
          title: 'Verification Complete',
          message: 'Your account has been verified. You can now access all features.',
          color: 'emerald',
        };
      case 'REJECTED':
        return {
          icon: <XCircle className="h-5 w-5 text-red-500" />,
          title: 'Verification Rejected',
          message: 'Your verification was not approved. Please contact support for assistance.',
          color: 'red',
        };
      default:
        return null;
    }
  };

  if (pageLoading) {
    return (
      <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-surface-sunken px-4 py-10">
        <div className="text-center">
          <div className="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-2 border-primary-500 border-t-transparent" />
          <p className="text-sm text-ink-muted">Loading verification page...</p>
        </div>
      </div>
    );
  }

  const statusDisplay = getStatusDisplay();

  return (
    <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-surface-sunken px-4 py-10">
      <div className="pointer-events-none absolute inset-0">
        <div className="absolute -left-40 -top-40 h-96 w-96 rounded-full bg-primary-500/20 blur-3xl" />
        <div className="absolute -bottom-40 -right-40 h-96 w-96 rounded-full bg-indigo-500/20 blur-3xl" />
        <div className="absolute inset-0 bg-grid opacity-40" />
      </div>

      <div className="relative mx-auto w-full max-w-lg">
        <div className="mb-6 text-center">
          <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-gradient-to-br from-primary-500 to-indigo-600 text-white">
            <Shield className="h-6 w-6" />
          </div>
          <h1 className="text-2xl font-bold text-ink">Account Verification</h1>
          <p className="mt-1 text-sm text-ink-muted">Complete verification to access all features</p>
        </div>

        <Card className="card-hover">
          {verificationData?.adminMessage && (
            <div className="border-b border-border p-5">
              <div className="flex items-start gap-3 rounded-xl border border-blue-500/30 bg-blue-500/10 p-4 text-sm text-blue-600 dark:text-blue-300">
                <FileText className="mt-0.5 h-5 w-5 shrink-0" />
                <div>
                  <p className="font-medium mb-1">Message from Administration</p>
                  <p className="whitespace-pre-wrap text-blue-600/90 dark:text-blue-300/90">
                    {verificationData.adminMessage}
                  </p>
                </div>
              </div>
            </div>
          )}

          {error && (
            <div className="mx-5 mt-4 flex items-start gap-2 rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-600 dark:text-red-300">
              <AlertTriangle className="mt-0.5 h-5 w-5 shrink-0" />
              <span>{error}</span>
            </div>
          )}

          {statusDisplay && (
            <div className="mx-5 mt-4 flex items-start gap-3 rounded-xl border border-{statusDisplay.color}-500/30 bg-{statusDisplay.color}-500/10 p-4 text-sm text-{statusDisplay.color}-600 dark:text-{statusDisplay.color}-300">
              {statusDisplay.icon}
              <div>
                <p className="font-medium">{statusDisplay.title}</p>
                <p className="mt-1 text-{statusDisplay.color}-600/80 dark:text-{statusDisplay.color}-300/80">
                  {statusDisplay.message}
                </p>
              </div>
            </div>
          )}

          {success || verificationData?.currentStatus === 'VERIFIED' ? (
            <CardContent className="pt-5">
              <div className="flex items-start gap-3 rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-4 text-sm text-emerald-600 dark:text-emerald-300">
                <CheckCircle2 className="mt-0.5 h-5 w-5 shrink-0" />
                <div>
                  <p className="font-medium">Verification Complete!</p>
                  <p className="mt-1 text-emerald-600/80 dark:text-emerald-300/80">
                    Your account has been verified. You can now access all features.
                  </p>
                </div>
              </div>
              <div className="mt-4">
                <a href="/login" className="block">
                  <Button className="w-full">
                    Continue to Login
                    <ArrowRight className="ml-2 h-4 w-4" />
                  </Button>
                </a>
              </div>
            </CardContent>
          ) : verificationData?.currentStatus === 'PENDING' ? (
            <CardContent className="pt-5">
              <p className="text-center text-sm text-ink-muted">
                Your verification is being reviewed. You will be notified once complete.
              </p>
            </CardContent>
          ) : (
            <form onSubmit={handleSubmit}>
              <CardContent className="space-y-4 pt-5">
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-ink">
                    Upload Verification Document <span className="text-red-500">*</span>
                  </label>
                  <div
                    className={`relative flex flex-col items-center justify-center rounded-xl border-2 border-dashed p-8 transition-colors ${
                      dragActive
                        ? 'border-primary-500 bg-primary-500/10'
                        : selectedFile
                        ? 'border-emerald-500/50 bg-emerald-500/5'
                        : 'border-border hover:border-primary-500/50 hover:bg-primary-500/5'
                    }`}
                    onDragEnter={handleDrag}
                    onDragLeave={handleDrag}
                    onDragOver={handleDrag}
                    onDrop={handleDrop}
                  >
                    {selectedFile ? (
                      <div className="text-center">
                        <FileText className="mx-auto mb-2 h-10 w-10 text-emerald-500" />
                        <p className="text-sm font-medium text-ink">{selectedFile.name}</p>
                        <p className="mt-1 text-xs text-ink-muted">
                          {(selectedFile.size / 1024 / 1024).toFixed(2)} MB
                        </p>
                        <button
                          type="button"
                          onClick={() => setSelectedFile(null)}
                          className="mt-2 text-xs text-red-500 hover:underline"
                        >
                          Remove
                        </button>
                      </div>
                    ) : (
                      <>
                        <Upload className="mb-3 h-10 w-10 text-ink-muted" />
                        <p className="text-sm font-medium text-ink">
                          Drag and drop your document here
                        </p>
                        <p className="mt-1 text-xs text-ink-muted">or</p>
                        <label className="mt-2 cursor-pointer text-sm font-medium text-primary-600 hover:underline">
                          Browse files
                          <input
                            type="file"
                            accept="image/jpeg,image/png,image/jpg,application/pdf"
                            onChange={handleFileChange}
                            className="hidden"
                          />
                        </label>
                        <p className="mt-2 text-xs text-ink-faint">
                          Accepted: JPEG, PNG, PDF (max {sysConfig.verificationMaxSizeMb}MB)
                        </p>
                      </>
                    )}
                  </div>
                </div>
                <Button type="submit" className="w-full" loading={loading} disabled={!selectedFile}>
                  {loading ? 'Uploading...' : 'Submit for Verification'}
                  {!loading && <ArrowRight className="ml-2 h-4 w-4" />}
                </Button>
              </CardContent>
            </form>
          )}

          <CardFooter className="justify-center">
            <p className="text-sm text-ink-muted">
              Need help?{' '}
              <a href="/support" className="font-semibold text-primary-600 hover:underline">
                Contact Support
              </a>
            </p>
          </CardFooter>
        </Card>
      </div>
    </div>
  );
}
