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

interface MangaDexImportDialogProps {
  mangaDexDialogOpen: boolean;
  onMangaDexDialogOpenChange: (open: boolean) => void;
}

export const MangaDexImportDialog = ({
  mangaDexDialogOpen,
  onMangaDexDialogOpenChange,
}: MangaDexImportDialogProps) => {
  const [mangaDexId, setMangaDexId] = useState("");

  const { mutate: importMangaDex, isPending: isPendingImportMangaDex } =
    useImportFromMangaDex({
      mutation: {
        onSuccess: () => {
          setMangaDexId("");
          onMangaDexDialogOpenChange(false);
          toast.success("Manga imported successfully!");
        },
      },
    });

  const handleMangaDexImport = () => {
    if (!mangaDexId.trim()) {
      alert("Please enter a MangaDex URL or ID");
      return;
    }

    let id = mangaDexId;
    if (mangaDexId.length > 36) {
      const match = mangaDexId.match(/title\/([0-9a-fA-F-]{36})/);
      if (match) {
        id = match[1];
      } else {
        alert("Invalid MangaDex URL or ID");
        return;
      }
    }

    if (id.length !== 36) {
      alert("Invalid MangaDex ID");
      return;
    }

    importMangaDex({ data: { id } });
  };

  return (
    <Dialog open={mangaDexDialogOpen} onOpenChange={onMangaDexDialogOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Import from MangaDex</DialogTitle>
          <DialogDescription>
            Enter a MangaDex manga URL or ID to import it to your library.
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          <div>
            <label className="text-sm font-medium">MangaDex URL or ID</label>
            <Input
              placeholder="e.g., https://mangadex.org/title/..."
              value={mangaDexId}
              onChange={(e) => setMangaDexId(e.target.value)}
              className="mt-2"
            />
          </div>
        </div>
        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onMangaDexDialogOpenChange(false)}
          >
            Cancel
          </Button>
          <Button
            disabled={isPendingImportMangaDex}
            onClick={handleMangaDexImport}
          >
            Import
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
