"use client";

import { useState, useEffect } from "react";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ScrollArea } from "@/components/ui/scroll-area";
import { AlertTriangle, ArrowRight, Check, X } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { RenameProposal, ProposeRenameResponse, BatchRenameResponse } from "@/types";

interface RenameDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    albumPath: string;
    onRenameComplete: () => void;
}

export function RenameDialog({ open, onOpenChange, albumPath, onRenameComplete }: RenameDialogProps) {
    const [loading, setLoading] = useState(false);
    const [proposals, setProposals] = useState<RenameProposal[]>([]);
    const [allFiles, setAllFiles] = useState<RenameProposal[]>([]);
    const [applyToAll, setApplyToAll] = useState(true);
    const [maxFileLength, setMaxFileLength] = useState(0);
    const [selectedStrategy, setSelectedStrategy] = useState<"remove_brackets" | "remove_parens" | "remove_both" | "truncate">("remove_both");
    const [renaming, setRenaming] = useState(false);

    useEffect(() => {
        if (open && albumPath) {
            fetchProposals();
        }
    }, [open, albumPath]);

    const fetchProposals = async () => {
        setLoading(true);
        try {
            const res = await fetch("/api/propose-rename", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ albumPath }),
            });
            const data = await res.json() as ProposeRenameResponse;
            if (data.success) {
                setProposals(data.problematicFiles);
                setAllFiles(data.allFiles || []);
                setMaxFileLength(data.maxFileLength);
            }
        } catch (e) {
            console.error("Failed to fetch proposals", e);
        } finally {
            setLoading(false);
        }
    };

    const handleRename = async () => {
        setRenaming(true);
        try {
            const activeProposals = applyToAll ? allFiles : proposals;
            const renames = activeProposals.map(p => ({
                original: p.original,
                newName: p.strategies[selectedStrategy] || p.strategies.truncate // Fallback to truncate if strategy returns null (shouldn't happen for truncate)
            }));

            const res = await fetch("/api/batch-rename", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ albumPath, renames }),
            });
            const result = await res.json() as BatchRenameResponse;

            if (result.success) {
                onRenameComplete();
                onOpenChange(false);
            } else {
                alert(`Rename failed: ${result.errors?.join(', ')}`);
            }
        } catch (e) {
            alert("Rename request failed");
        } finally {
            setRenaming(false);
        }
    };

    const getPreview = (proposal: RenameProposal) => {
        const newName = proposal.strategies[selectedStrategy];
        if (!newName) return <span className="text-red-500 italic">Strategy not applicable (still too long)</span>;
        return <span className="text-green-500 font-medium">{newName}</span>;
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-4xl max-h-[80vh] flex flex-col">
                <DialogHeader>
                    <DialogTitle className="flex items-center gap-2 text-destructive">
                        <AlertTriangle className="w-5 h-5" />
                        Long Filenames Detected
                    </DialogTitle>
                    <DialogDescription>
                        The following files exceed the maximum allowed length ({maxFileLength} characters).
                        Please select a renaming strategy to fix them.
                    </DialogDescription>
                </DialogHeader>

                <div className="flex-1 flex flex-col min-h-0 gap-4 py-4">
                    <Tabs value={selectedStrategy} onValueChange={(v) => setSelectedStrategy(v as "remove_brackets" | "remove_parens" | "remove_both" | "truncate")} className="flex-1 flex flex-col min-h-0">
                        <TabsList className="grid w-full grid-cols-4">
                            <TabsTrigger value="remove_brackets">Remove []</TabsTrigger>
                            <TabsTrigger value="remove_parens">Remove ()</TabsTrigger>
                            <TabsTrigger value="remove_both">Remove Both</TabsTrigger>
                            <TabsTrigger value="truncate">Smart Truncate</TabsTrigger>
                        </TabsList>

                        <div className="flex items-center gap-2 mt-4">
                            <label className="flex items-center gap-2 text-sm text-muted-foreground cursor-pointer select-none hover:text-foreground transition-colors overflow-hidden">
                                <input
                                    type="checkbox"
                                    checked={applyToAll}
                                    onChange={(e) => setApplyToAll(e.target.checked)}
                                    className="w-4 h-4 rounded border-white/20 bg-black/20 text-primary focus:ring-primary/50"
                                />
                                Apply chosen resolution to all files in the album
                            </label>
                        </div>
                        <div className="flex-1 border rounded-md mt-4 overflow-hidden bg-muted/20">
                            <ScrollArea className="h-[400px] p-4">
                                <div className="space-y-4">
                                    {(applyToAll ? allFiles : proposals).map((p, i) => (
                                        <div key={i} className="grid grid-cols-[1fr_auto_1fr] gap-4 items-center text-sm border-b border-border/50 pb-4 last:border-0 last:pb-0">
                                            <div className="break-all text-muted-foreground">
                                                {p.original}
                                                <Badge variant="outline" className="ml-2 text-xs">{p.original.length}</Badge>
                                            </div>
                                            <ArrowRight className="w-4 h-4 text-muted-foreground/50" />
                                            <div className="break-all">
                                                {getPreview(p)}
                                                {p.strategies[selectedStrategy] && (
                                                    <Badge variant="outline" className="ml-2 text-xs border-green-500/30 text-green-500">
                                                        {p.strategies[selectedStrategy]!.length}
                                                    </Badge>
                                                )}
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </ScrollArea>
                        </div>
                    </Tabs>
                </div>

                <DialogFooter className="gap-2 sm:gap-0">
                    <Button variant="ghost" onClick={() => onOpenChange(false)}>
                        Ignore & Close
                    </Button>
                    <Button onClick={handleRename} disabled={renaming}>
                        {renaming ? "Renaming..." : "Apply Changes"}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
