'use client';

import React, { useState } from 'react';
import { Edit2, Save, X, Info, Tag, FlaskConical, CircleDollarSign, Search, Loader2, ExternalLink } from 'lucide-react';
import { updateBottle } from '@/services/update-bottle';
import { discoverWhiskybaseId } from '@/services/discover-whiskybase';
import { useI18n } from '@/i18n/I18nContext';

interface EditBottleFormProps {
    bottle: {
        id: string;
        name: string;
        distillery: string;
        category: string;
        abv: number;
        age: number;
        whiskybase_id: string | null;
        purchase_price?: number | null;
        distilled_at?: string | null;
        bottled_at?: string | null;
        batch_info?: string | null;
        cask_type?: string | null;
    };
    onComplete?: () => void;
}

export default function EditBottleForm({ bottle, onComplete }: EditBottleFormProps) {
    const { t, locale } = useI18n();
    const [isEditing, setIsEditing] = useState(false);
    const [isSaving, setIsSaving] = useState(false);
    const [isSearching, setIsSearching] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [discoveryResult, setDiscoveryResult] = useState<{ id: string; url: string; title: string } | null>(null);

    const [formData, setFormData] = useState({
        name: bottle.name,
        distillery: bottle.distillery || '',
        category: bottle.category || '',
        abv: bottle.abv?.toString() || '',
        age: bottle.age?.toString() || '',
        whiskybase_id: bottle.whiskybase_id || '',
        purchase_price: bottle.purchase_price?.toString() || '',
        distilled_at: bottle.distilled_at || '',
        bottled_at: bottle.bottled_at || '',
        batch_info: bottle.batch_info || '',
        cask_type: bottle.cask_type || '',
    });

    const handleDiscover = async () => {
        setIsSearching(true);
        setError(null);
        setDiscoveryResult(null);

        const result = await discoverWhiskybaseId({
            name: formData.name,
            distillery: formData.distillery,
            abv: formData.abv ? parseFloat(formData.abv) : undefined,
            age: formData.age ? parseInt(formData.age) : undefined,
            distilled_at: formData.distilled_at || undefined,
            bottled_at: formData.bottled_at || undefined,
            batch_info: formData.batch_info || undefined,
        });

        if (result.success && result.id) {
            setDiscoveryResult({ id: result.id!, url: result.url!, title: result.title! });
        } else {
            setError(result.error || t('bottle.noMatchFound'));
        }
        setIsSearching(false);
    };

    const applyDiscovery = () => {
        if (discoveryResult) {
            setFormData({ ...formData, whiskybase_id: discoveryResult.id });
            setDiscoveryResult(null);
        }
    };

    const handleSave = async () => {
        setIsSaving(true);
        setError(null);

        try {
            const response = await updateBottle(bottle.id, {
                ...formData,
                abv: formData.abv ? parseFloat(formData.abv.replace(',', '.')) : null,
                age: formData.age ? parseInt(formData.age) : null,
                purchase_price: formData.purchase_price ? parseFloat(formData.purchase_price.replace(',', '.')) : null,
                distilled_at: formData.distilled_at || undefined,
                bottled_at: formData.bottled_at || undefined,
                batch_info: formData.batch_info || undefined,
                cask_type: formData.cask_type || undefined,
            } as any);

            if (response.success) {
                setIsEditing(false);
                if (onComplete) onComplete();
            } else {
                setError(response.error || t('common.error'));
            }
        } catch (err) {
            setError(t('common.error'));
        } finally {
            setIsSaving(false);
        }
    };

    return (
        <div className="space-y-6 animate-in fade-in slide-in-from-right-4 duration-500">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                {/* Full Width Inputs */}
                <div className="space-y-2 md:col-span-2">
                    <label className="text-[10px] font-black uppercase text-zinc-500 ml-1 tracking-widest">{t('bottle.nameLabel')}</label>
                    <input
                        type="text"
                        value={formData.name}
                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                        className="w-full px-5 py-4 bg-black/40 border border-white/5 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-100 text-sm font-bold transition-all placeholder:text-zinc-700"
                    />
                </div>

                <div className="space-y-2 md:col-span-2">
                    <label className="text-[10px] font-black uppercase text-zinc-500 ml-1 tracking-widest">{t('bottle.distilleryLabel')}</label>
                    <input
                        type="text"
                        value={formData.distillery}
                        onChange={(e) => setFormData({ ...formData, distillery: e.target.value })}
                        className="w-full px-5 py-4 bg-black/40 border border-white/5 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-100 text-sm font-bold transition-all placeholder:text-zinc-700"
                    />
                </div>

                {/* Compact Row: Category */}
                <div className="space-y-2">
                    <label className="text-[10px] font-black uppercase text-zinc-500 ml-1 tracking-widest">{t('bottle.categoryLabel')}</label>
                    <input
                        type="text"
                        value={formData.category}
                        onChange={(e) => setFormData({ ...formData, category: e.target.value })}
                        className="w-full px-5 py-4 bg-black/40 border border-white/5 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-100 text-sm font-bold transition-all placeholder:text-zinc-700"
                    />
                </div>

                {/* Row A: ABV + Age */}
                <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                        <label className="text-[10px] font-black uppercase text-zinc-500 ml-1 tracking-widest">{t('bottle.abvLabel')}</label>
                        <input
                            type="text"
                            inputMode="decimal"
                            value={formData.abv}
                            onChange={(e) => setFormData({ ...formData, abv: e.target.value })}
                            className="w-full px-5 py-4 bg-black/40 border border-white/5 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-orange-500 text-sm font-bold transition-all"
                            placeholder="e.g. 46.3"
                        />
                    </div>
                    <div className="space-y-2">
                        <label className="text-[10px] font-black uppercase text-zinc-500 ml-1 tracking-widest">{t('bottle.ageLabel')}</label>
                        <input
                            type="text"
                            inputMode="numeric"
                            value={formData.age}
                            onChange={(e) => setFormData({ ...formData, age: e.target.value })}
                            className="w-full px-5 py-4 bg-black/40 border border-white/5 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-100 text-sm font-bold transition-all"
                            placeholder="e.g. 12"
                        />
                    </div>
                </div>

                {/* Row B: Distilled + Bottled */}
                <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                        <label className="text-[10px] font-black uppercase text-zinc-500 ml-1 tracking-widest">{t('bottle.distilledLabel')}</label>
                        <input
                            type="text"
                            inputMode="numeric"
                            placeholder="YYYY"
                            value={formData.distilled_at}
                            onChange={(e) => setFormData({ ...formData, distilled_at: e.target.value })}
                            className="w-full px-5 py-4 bg-black/40 border border-white/5 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-100 text-sm font-bold transition-all placeholder:text-zinc-700"
                        />
                    </div>
                    <div className="space-y-2">
                        <label className="text-[10px] font-black uppercase text-zinc-500 ml-1 tracking-widest">{t('bottle.bottledLabel')}</label>
                        <input
                            type="text"
                            inputMode="numeric"
                            placeholder="YYYY"
                            value={formData.bottled_at}
                            onChange={(e) => setFormData({ ...formData, bottled_at: e.target.value })}
                            className="w-full px-5 py-4 bg-black/40 border border-white/5 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-100 text-sm font-bold transition-all placeholder:text-zinc-700"
                        />
                    </div>
                </div>

                {/* Price and WB ID Row */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:col-span-2">
                    <div className="space-y-2">
                        <label className="text-[10px] font-black uppercase text-zinc-500 ml-1 tracking-widest">{t('bottle.priceLabel')} (€)</label>
                        <input
                            type="text"
                            inputMode="decimal"
                            placeholder="0.00"
                            value={formData.purchase_price}
                            onChange={(e) => setFormData({ ...formData, purchase_price: e.target.value })}
                            className="w-full px-5 py-4 bg-black/40 border border-white/5 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 font-bold text-orange-500 text-sm transition-all"
                        />
                    </div>

                    <div className="space-y-2">
                        <label className="text-[10px] font-black uppercase text-zinc-500 ml-1 flex justify-between items-center tracking-widest">
                            <span>Whiskybase ID</span>
                            <button
                                type="button"
                                onClick={handleDiscover}
                                disabled={isSearching}
                                className="text-orange-600 hover:text-orange-500 flex items-center gap-1.5 normal-case font-black text-[9px] tracking-widest transition-colors"
                            >
                                {isSearching ? <Loader2 size={12} className="animate-spin" /> : <Search size={12} />}
                                {t('bottle.autoSearch')}
                            </button>
                        </label>
                        <div className="relative">
                            <input
                                type="text"
                                inputMode="numeric"
                                value={formData.whiskybase_id}
                                onChange={(e) => setFormData({ ...formData, whiskybase_id: e.target.value })}
                                className="w-full px-5 py-4 bg-black/40 border border-white/5 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-300 text-sm font-mono transition-all"
                            />
                            {discoveryResult && (
                                <div className="absolute top-full left-0 right-0 z-50 mt-3 p-4 bg-zinc-900 border border-orange-500/30 rounded-2xl shadow-2xl animate-in zoom-in-95 duration-300">
                                    <p className="text-[9px] font-black uppercase tracking-widest text-zinc-500 mb-2">Recommendation:</p>
                                    <p className="text-[12px] font-black text-zinc-100 mb-4 line-clamp-2 leading-tight">{discoveryResult.title}</p>
                                    <div className="flex gap-2">
                                        <button
                                            type="button"
                                            onClick={applyDiscovery}
                                            className="flex-1 py-3 bg-orange-600 hover:bg-orange-500 text-white text-[10px] font-black uppercase tracking-widest rounded-xl transition-colors shadow-lg shadow-orange-950/20"
                                        >
                                            Accept ID
                                        </button>
                                        <a
                                            href={discoveryResult.url}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="px-4 py-3 bg-zinc-800 hover:bg-zinc-700 text-zinc-400 rounded-xl flex items-center justify-center border border-white/5 transition-colors"
                                        >
                                            <ExternalLink size={14} />
                                        </a>
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                </div>

                {/* Batch and Cask */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:col-span-2">
                    <div className="space-y-2">
                        <label className="text-[10px] font-black uppercase text-zinc-500 ml-1 tracking-widest">{t('bottle.batchLabel')}</label>
                        <input
                            type="text"
                            placeholder="e.g. Batch 12 or L-Code"
                            value={formData.batch_info}
                            onChange={(e) => setFormData({ ...formData, batch_info: e.target.value })}
                            className="w-full px-5 py-4 bg-black/40 border border-white/5 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-100 text-sm font-bold transition-all placeholder:text-zinc-700"
                        />
                    </div>
                    <div className="space-y-2">
                        <label className="text-[10px] font-black uppercase text-zinc-500 ml-1 tracking-widest">Fass-Typ (Cask)</label>
                        <input
                            type="text"
                            placeholder="e.g. Oloroso Sherry"
                            value={formData.cask_type}
                            onChange={(e) => setFormData({ ...formData, cask_type: e.target.value })}
                            className="w-full px-5 py-4 bg-black/40 border border-white/5 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-100 text-sm font-bold transition-all placeholder:text-zinc-700"
                        />
                    </div>
                </div>
            </div>

            {error && (
                <div className="p-3 bg-red-500/10 border border-red-500/20 rounded-xl flex items-center gap-2 text-red-500 text-[10px] font-bold">
                    <Info size={14} />
                    {error}
                </div>
            )}

            <div className="flex gap-3 pt-2">
                <button
                    onClick={() => onComplete?.()}
                    className="flex-1 py-4 bg-zinc-800 hover:bg-zinc-700 text-zinc-400 rounded-2xl font-black uppercase tracking-widest text-xs transition-all"
                >
                    {t('common.cancel')}
                </button>
                <button
                    onClick={handleSave}
                    disabled={isSaving}
                    className="flex-[2] py-4 bg-orange-600 hover:bg-orange-700 text-white rounded-2xl font-black uppercase tracking-widest text-xs transition-all flex items-center justify-center gap-2 shadow-xl shadow-orange-950/20 disabled:opacity-50"
                >
                    {isSaving ? <Loader2 size={16} className="animate-spin" /> : <Save size={16} />}
                    {t('bottle.saveChanges')}
                </button>
            </div>
        </div>
    );
}
