import { Button } from "@/components/ui/button";
import { FileUp } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import React, { useState } from "react";
import { Input } from "@/components/ui/input";
import { useImportMultipleFiles } from "@/api/mangamochi";
import { toast } from "sonner";

interface MangaManualImportDialogProps {
  fileImportDialogOpen: boolean;
  onFileImportDialogOpenChange: (open: boolean) => void;
}

export const MangaManualImportDialog = ({
  fileImportDialogOpen,
  onFileImportDialogOpenChange,
}: MangaManualImportDialogProps) => {
  const [malId, setMalId] = useState("");
  const [dragActive, setDragActive] = useState(false);
  const [files, setFiles] = useState<File[] | null>(null);

  const { mutate, isPending } = useImportMultipleFiles({
    mutation: {
      onSuccess: () => {
        setFiles(null);
        setMalId("");
        onFileImportDialogOpenChange(false);
        toast.success("Manga imported successfully!");
      },
      onError: () => toast.error("Failed to import manga."),
    },
  });

  const handleFileImport = () => {
    if (!files) {
      alert("Please select one or more files to upload");
      return;
    }

    if (!malId.trim()) {
      alert("Please enter a MyAnimeList manga ID");
      return;
    }

    let id = malId;

    if (!/^\d+$/.test(malId)) {
      const regex =
        /https?:\/\/(?:www\.)?myanimelist\.net\/(manga)\/(\d+)(?:\/|$)/i;
      const match = malId.match(regex);

      if (match) {
        id = match[2];
      } else {
        alert("Invalid MyAnimeList URL or ID");
        return;
      }
    }

    mutate({ data: { malId: id, files } });
  };

  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) {
      setFiles(Array.from(e.dataTransfer.files));
    }
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      setFiles(Array.from(e.target.files));
    }
  };

  return (
    <Dialog
      open={fileImportDialogOpen}
      onOpenChange={onFileImportDialogOpenChange}
    >
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Import from File</DialogTitle>
          <DialogDescription>
            Upload one or more files and provide the MyAnimeList manga URL (or
            ID) to import manga data.
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          <div>
            <label className="text-sm font-medium">
              MyAnimeList Manga URL (or ID)
            </label>
            <Input
              placeholder="e.g., https://myanimelist.net/manga/..."
              value={malId}
              onChange={(e) => setMalId(e.target.value)}
              className="mt-2"
            />
          </div>
          <div>
            <label className="text-sm font-medium">Upload File</label>
            <div
              onDragEnter={handleDrag}
              onDragLeave={handleDrag}
              onDragOver={handleDrag}
              onDrop={handleDrop}
              className={`mt-2 rounded-lg border-2 border-dashed p-6 text-center transition-colors ${
                dragActive
                  ? "border-primary bg-primary/5"
                  : "border-muted-foreground/25"
              }`}
            >
              <input
                type="file"
                id="file-input"
                onChange={handleFileSelect}
                className="hidden"
                multiple
                accept=".cbz"
              />
              <label htmlFor="file-input" className="cursor-pointer">
                <div className="flex flex-col items-center gap-2">
                  <FileUp className="h-8 w-8 text-muted-foreground" />
                  <div>
                    <p className="text-sm font-medium">
                      {files
                        ? files.map((file) => file.name).join(", ")
                        : "Drag and drop your files here"}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      or click to select (.CBZ, .CBR)
                    </p>
                  </div>
                </div>
              </label>
            </div>
          </div>
        </div>
        <DialogFooter>
          <Button
            disabled={isPending}
            variant="outline"
            onClick={() => {
              setFiles(null);
              onFileImportDialogOpenChange(false);
            }}
          >
            Cancel
          </Button>
          <Button disabled={isPending} onClick={handleFileImport}>
            Import
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
