import { useState, useCallback } from "react";
import { useDropzone } from "react-dropzone";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Progress } from "@/components/ui/progress";
import { Upload, FileText, AlertCircle } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { supabase } from "@/lib/supabase";
import { useShop } from "@/components/context/ShopContext";
import { useTranslation } from 'react-i18next';

interface CustomContentUploadProps {
  onSuccess: () => void;
}

export function CustomContentUpload({ onSuccess }: CustomContentUploadProps) {
  const { t } = useTranslation();
  const [file, setFile] = useState<File | null>(null);
  const [title, setTitle] = useState("");
  const [uploading, setUploading] = useState(false);
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const { toast } = useToast();
  const { selectedShop } = useShop();

  const onDrop = useCallback((acceptedFiles: File[]) => {
    if (acceptedFiles.length > 0) {
      const uploadedFile = acceptedFiles[0];
      setFile(uploadedFile);
      // Auto-fill title with filename (without extension)
      const fileName = uploadedFile.name.replace(/\.pdf$/i, "");
      setTitle(fileName);
      setError(null);
    }
  }, []);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: {
      'application/pdf': ['.pdf']
    },
    maxFiles: 1,
    maxSize: 10 * 1024 * 1024, // 10MB
  });

  const handleUpload = async () => {
    if (!file || !title.trim()) {
      setError(t('customContent.upload.errorRequired'));
      return;
    }

    if (!selectedShop) {
      setError(t('customContent.upload.errorSelectShop'));
      return;
    }

    setUploading(true);
    setError(null);
    setProgress(10);

    try {
      // Create FormData
      const formData = new FormData();
      formData.append("file", file);
      formData.append("title", title.trim());
      formData.append("store_id", selectedShop.id);

      setProgress(30);

      // Get auth token
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) {
        throw new Error("Not authenticated");
      }

      setProgress(50);

      // Upload to Edge Function
      const response = await fetch(
        `${import.meta.env.VITE_API_URL}/custom-content-upload`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${session.access_token}`,
          },
          body: formData,
        }
      );

      setProgress(80);

      const result = await response.json();

      if (!response.ok) {
        if (result.duplicate) {
          throw new Error(
            t('customContent.upload.errorDuplicate', {
              title: result.existingContent.title,
              date: new Date(result.existingContent.uploadedAt).toLocaleDateString()
            })
          );
        }
        throw new Error(result.error || t('customContent.upload.errorTitle'));
      }

      setProgress(100);

      toast({
        title: t('customContent.upload.successTitle'),
        description: t('customContent.upload.successDescription', { fileName: result.fileName }),
      });

      onSuccess();
    } catch (err: any) {
      console.error("Upload error:", err);
      setError(err.message || t('customContent.upload.errorTitle'));
      toast({
        title: t('customContent.upload.errorTitle'),
        description: err.message || t('customContent.upload.errorTitle'),
        variant: "destructive",
      });
    } finally {
      setUploading(false);
      setProgress(0);
    }
  };

  return (
    <div className="space-y-4 bg-slate-800 p-6 rounded-lg">
      <div>
        <h2 className="text-lg font-semibold text-white">{t('customContent.upload.title')}</h2>
        <p className="text-sm text-slate-400">
          {t('customContent.upload.description')}
        </p>
      </div>

      {/* File Dropzone */}
      <div
        {...getRootProps()}
        className={`
          border-2 border-dashed rounded-lg p-8 text-center cursor-pointer
          transition-colors
          ${isDragActive ? "border-cyan-500 bg-cyan-500/10" : "border-slate-600"}
          ${file ? "bg-slate-700" : "bg-slate-900"}
        `}
      >
        <input {...getInputProps()} />
        {file ? (
          <div className="flex items-center justify-center gap-2">
            <FileText className="h-8 w-8 text-cyan-400" />
            <div className="text-left">
              <p className="font-medium text-white">{file.name}</p>
              <p className="text-sm text-slate-400">
                {(file.size / 1024 / 1024).toFixed(2)} MB
              </p>
            </div>
          </div>
        ) : (
          <div>
            <Upload className="h-12 w-12 mx-auto text-slate-400 mb-2" />
            <p className="text-sm text-slate-300">
              {isDragActive
                ? t('customContent.upload.dragDrop')
                : t('customContent.upload.dragDrop')}
            </p>
            <p className="text-xs text-slate-500 mt-1">
              {t('customContent.upload.maxSize')}
            </p>
          </div>
        )}
      </div>

      {/* Title Input */}
      <div className="space-y-2">
        <Label htmlFor="title" className="text-slate-300">{t('customContent.upload.titleLabel')} *</Label>
        <Input
          id="title"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          placeholder={t('customContent.upload.titlePlaceholder')}
          disabled={uploading}
          className="bg-slate-900 border-slate-600 text-white placeholder:text-slate-500"
        />
      </div>

      {/* Progress Bar */}
      {uploading && (
        <div className="space-y-2">
          <Progress value={progress} className="bg-slate-700" />
          <p className="text-sm text-center text-slate-400">
            {t('customContent.upload.uploading')} {progress}%
          </p>
        </div>
      )}

      {/* Error Alert */}
      {error && (
        <Alert variant="destructive" className="bg-red-900/20 border-red-800">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription className="text-red-200">{error}</AlertDescription>
        </Alert>
      )}

      {/* Action Buttons */}
      <div className="flex justify-end gap-2">
        <Button
          variant="outline"
          onClick={() => onSuccess()}
          disabled={uploading}
          className="bg-slate-700 border-slate-600 text-white hover:bg-slate-600"
        >
          {t('customContent.upload.cancel')}
        </Button>
        <Button
          onClick={handleUpload}
          disabled={!file || !title.trim() || uploading}
          className="bg-cyan-500 hover:bg-cyan-600 text-white"
        >
          {uploading ? t('customContent.upload.uploading') : t('customContent.upload.upload')}
        </Button>
      </div>
    </div>
  );
}
