"use client";

import React from 'react';
import { X, Wand2, Loader2, Sparkles, Lock } from 'lucide-react';
import { cn } from '@/lib/utils';

interface EditPromptModalProps {
    isOpen: boolean;
    onClose: () => void;
    image: { data: string; prompt: string; provider?: string } | null;
    onGenerate: (prompt: string, options: { keepSubject: boolean; keepScene: boolean; keepStyle: boolean }) => Promise<void>;
}

export function EditPromptModal({ isOpen, onClose, image, onGenerate }: EditPromptModalProps) {
    const [prompt, setPrompt] = React.useState('');
    const [loading, setLoading] = React.useState(false);
    const [keepSubject, setKeepSubject] = React.useState(true);
    const [keepScene, setKeepScene] = React.useState(true);
    const [keepStyle, setKeepStyle] = React.useState(true);

    const isMeta = image?.provider === 'meta';

    React.useEffect(() => {
        if (isOpen && image) {
            setPrompt(image.prompt);
        }
    }, [isOpen, image]);

    // ... (lines 27-130 remain unchanged, so we skip them in replace tool if possible, 

    if (!isOpen) return null;

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);
        try {
            await onGenerate(prompt, { keepSubject, keepScene, keepStyle });
            onClose();
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const ConsistencyToggle = ({
        label,
        checked,
        onChange,
        color
    }: {
        label: string;
        checked: boolean;
        onChange: (v: boolean) => void;
        color: string;
    }) => (
        <button
            type="button"
            onClick={() => onChange(!checked)}
            className={cn(
                "flex items-center gap-2 px-3 py-2 rounded-lg border text-xs font-medium transition-all",
                checked
                    ? `${color} border-current/20 bg-current/10`
                    : "text-white/40 border-white/10 hover:border-white/20"
            )}
        >
            <Lock className={cn("h-3.5 w-3.5", checked ? "opacity-100" : "opacity-30")} />
            <span>{label}</span>
        </button>
    );

    return (
        <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/90 backdrop-blur-md p-4 animate-in fade-in duration-300">
            {/* Modal Container */}
            <div className="relative w-full max-w-2xl bg-[#1a1a1e] rounded-2xl border border-white/10 shadow-2xl shadow-black/50 overflow-hidden">

                {/* Close Button */}
                <button
                    onClick={onClose}
                    className="absolute top-4 right-4 p-2 hover:bg-white/10 rounded-full transition-colors z-10 text-white/70 hover:text-white"
                >
                    <X className="h-5 w-5" />
                </button>

                {/* Header with Gradient */}
                <div className="relative px-6 pt-6 pb-4">
                    <div className="absolute inset-0 bg-gradient-to-br from-amber-500/10 via-transparent to-purple-500/10 pointer-events-none" />
                    <div className="flex items-center gap-4 relative">
                        <div className="p-3 bg-gradient-to-br from-amber-500/20 to-purple-500/20 rounded-xl border border-white/10 backdrop-blur-sm">
                            <Wand2 className="h-6 w-6 text-amber-400" />
                        </div>
                        <div>
                            <h2 className="text-xl font-semibold text-white">Remix Image</h2>
                            <p className="text-sm text-white/50">Generate a variation with consistent elements</p>
                        </div>
                    </div>
                </div>

                {/* Content */}
                <div className="px-6 pb-6">
                    {/* Image Preview & Input Row */}
                    <div className="flex gap-5">
                        {/* Image Preview */}
                        <div className="relative w-32 h-32 shrink-0 rounded-xl overflow-hidden border border-white/10 group">
                            {image && (
                                <>
                                    <img
                                        src={`data:image/png;base64,${image.data}`}
                                        alt="Source"
                                        className="w-full h-full object-cover"
                                    />
                                    <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex items-end justify-center pb-2">
                                        <span className="text-[10px] text-white/80 font-medium">Reference</span>
                                    </div>
                                </>
                            )}
                        </div>

                        {/* Prompt Input */}
                        <div className="flex-1 flex flex-col gap-3">
                            <label className="text-sm font-medium text-white/70 flex items-center gap-2">
                                <Sparkles className="h-3.5 w-3.5 text-amber-400" />
                                New Prompt
                            </label>
                            <textarea
                                value={prompt}
                                onChange={(e) => setPrompt(e.target.value)}
                                className="w-full h-24 p-3 rounded-xl bg-white/5 border border-white/10 resize-none focus:ring-2 focus:ring-amber-500/50 focus:border-amber-500/50 outline-none text-sm text-white placeholder:text-white/30 transition-all"
                                placeholder={isMeta ? "Modify your prompt to generate a new variation..." : "Describe your remix... The selected consistency options will be preserved..."}
                                autoFocus
                            />
                        </div>
                    </div>

                    {/* Consistency Toggles */}
                    {!isMeta && (
                        <div className="mt-4">
                            <label className="text-xs font-medium text-white/50 mb-2 block">Keep Consistent:</label>
                            <div className="flex flex-wrap gap-2">
                                <ConsistencyToggle
                                    label="Subject"
                                    checked={keepSubject}
                                    onChange={setKeepSubject}
                                    color="text-blue-400"
                                />
                                <ConsistencyToggle
                                    label="Scene"
                                    checked={keepScene}
                                    onChange={setKeepScene}
                                    color="text-green-400"
                                />
                                <ConsistencyToggle
                                    label="Style"
                                    checked={keepStyle}
                                    onChange={setKeepStyle}
                                    color="text-purple-400"
                                />
                            </div>
                        </div>
                    )}

                    {/* Info about consistency */}
                    {!isMeta && (
                        <div className="mt-4 p-3 bg-white/5 rounded-xl border border-white/10">
                            <p className="text-xs text-white/50">
                                <span className="text-amber-400">💡</span> Locked elements will be used as references to maintain visual consistency across generations.
                            </p>
                        </div>
                    )}

                    {/* Actions */}
                    <div className="flex justify-end gap-3 mt-6">
                        <button
                            onClick={onClose}
                            className="px-5 py-2.5 hover:bg-white/5 rounded-xl text-sm font-medium text-white/70 hover:text-white transition-colors"
                            disabled={loading}
                        >
                            Cancel
                        </button>
                        <button
                            onClick={handleSubmit}
                            disabled={loading || !prompt.trim()}
                            className={cn(
                                "px-6 py-2.5 rounded-xl text-sm font-semibold transition-all flex items-center gap-2",
                                "bg-gradient-to-r from-amber-500 to-purple-600 hover:from-amber-400 hover:to-purple-500",
                                "text-white shadow-lg shadow-amber-500/25",
                                "disabled:opacity-50 disabled:cursor-not-allowed disabled:shadow-none"
                            )}
                        >
                            {loading ? (
                                <>
                                    <Loader2 className="h-4 w-4 animate-spin" />
                                    <span>Generating...</span>
                                </>
                            ) : (
                                <>
                                    <Wand2 className="h-4 w-4" />
                                    <span>Remix</span>
                                </>
                            )}
                        </button>
                    </div>
                </div>

                {/* Loading Overlay */}
                {loading && (
                    <div className="absolute inset-0 bg-black/60 backdrop-blur-sm flex flex-col items-center justify-center gap-4 animate-in fade-in">
                        <div className="relative">
                            <div className="w-16 h-16 rounded-full border-2 border-amber-500/30" />
                            <div className="absolute inset-0 w-16 h-16 rounded-full border-2 border-t-amber-500 animate-spin" />
                        </div>
                        <div className="text-center">
                            <p className="text-white font-medium">Creating your remix...</p>
                            <p className="text-white/50 text-sm">Preserving selected elements</p>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}
