import React, { useState, useEffect } from 'react';
import {
    PawPrint, Heart, Sparkles, Cat, Hash,
    Globe, BookOpen, Shield, Calendar,
    Settings2, AlertCircle, X, Save, RefreshCw, Copy, Check, ExternalLink, User as UserIcon
} from 'lucide-react';

// Pobieramy adres API
const API_BASE = import.meta.env.VITE_API_TARGET;

// Nazwa klucza w localStorage, gdzie trzymasz token
const TOKEN_KEY = 'jwt_token';

type CaseType = 'upper' | 'lower' | 'mixed';

interface GeneratorSettings {
    length: number;
    alphanum: boolean;
    case: CaseType;
    withSubdomain: boolean;
}

interface LinkFormData {
    remoteUrl: string;
    uri: string;
    subdomain: string;
    privacy: boolean;
    expiryDate: string;
}

interface LinkPayload {
    remoteUrl: string;
    uri: string;
    subdomain?: string;
    privacy: boolean;
    expiryDate: number;
    userId?: string;
}

interface User {
    id: string;
    username: string; 
    email?: string;
}

export const Generator: React.FC = () => {
    const [user, setUser] = useState<User | null>(null);

    // Stan formularza głównego
    const [formData, setFormData] = useState<LinkFormData>({
        remoteUrl: '',
        uri: '',
        subdomain: '',
        privacy: true,
        expiryDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
    });

    // Stan ustawień generatora (GET)
    const [genSettings, setGenSettings] = useState<GeneratorSettings>({
        length: 6,
        alphanum: true,
        case: 'mixed',
        withSubdomain: false
    });

    // Stany UI
    const [loading, setLoading] = useState(false);
    const [generatingUri, setGeneratingUri] = useState(false);
    const [errorMsg, setErrorMsg] = useState<string | null>(null);
    const [result, setResult] = useState<string | null>(null);
    const [copied, setCopied] = useState(false);

    // Helper do pobierania nagłówków z tokenem
    const getAuthHeaders = () => {
        const token = localStorage.getItem(TOKEN_KEY);
        return {
            'Content-Type': 'application/json',
            ...(token ? { 'Authorization': `Bearer ${token}` } : {})
        };
    };

    // 1. Sprawdzenie sesji użytkownika przy starcie (używając JWT)
    // 1. Sprawdzenie sesji użytkownika przy starcie
    useEffect(() => {
        const checkUser = async () => {
            const token = localStorage.getItem(TOKEN_KEY);

            // Jeśli brak tokena, przerywamy (tryb gościa)
            if (!token) return;

            try {
                const res = await fetch(`${API_BASE}/api/v1/user/account`, {
                    headers: getAuthHeaders()
                });

                if (res.ok) {
                    const data = await res.json();

                    // Naprawa "Logged in as undefined":
                    // API może zwracać 'name', 'username' lub tylko 'email'
                    setUser({
                        id: data.id || data._id || data.userId,
                        username: data.username || data.name || data.email || "User",
                        email: data.email
                    });
                } else {
                    // Jeśli token jest nieważny (401), czyścimy go
                    console.log("Session expired. Logging out.");
                    localStorage.removeItem(TOKEN_KEY);
                    setUser(null);
                }
            } catch {
                // POPRAWKA: Usunęliśmy '(err)', teraz jest samo 'catch'
                // Dzięki temu linter nie krzyczy o nieużywaną zmienną
                console.log("API unreachable");
            }
        };
        checkUser();
    }, []);

    // 2. Generowanie URI (GET) - tutaj auth zazwyczaj nie jest wymagany, ale można dodać
    const handleGenerateUri = async (type: 'random' | 'wordlist') => {
        setGeneratingUri(true);
        setErrorMsg(null);
        try {
            let endpoint = '';
            const params = new URLSearchParams();

            params.append('withSubdomain', genSettings.withSubdomain.toString());

            if (type === 'random') {
                endpoint = '/api/v1/link/short';
                params.append('length', genSettings.length.toString());
                params.append('alphanum', genSettings.alphanum.toString());

                if (genSettings.case !== 'mixed') {
                    params.append('case', genSettings.case);
                }
            } else {
                endpoint = '/api/v1/link/fromWordlist';
            }

            // GET zazwyczaj jest publiczny, więc nie musimy dodawać Bearera, 
            // ale jeśli API tego wymaga, dodaj: headers: getAuthHeaders()
            const response = await fetch(`${API_BASE}${endpoint}?${params.toString()}`);
            const data = await response.json();

            if (!response.ok) throw new Error(data.error || 'Generation failed');

            const generatedUri = data.uri || data.shortUrl || data.link || "";
            setFormData(prev => ({ ...prev, uri: generatedUri }));

        } catch (err: unknown) {
            if (err instanceof Error) setErrorMsg(err.message);
        } finally {
            setGeneratingUri(false);
        }
    };

    // 3. Zapis do bazy (POST) - WYMAGA AUTH (JWT)
    const handleSubmitToDb = async () => {
        if (!formData.remoteUrl) {
            setErrorMsg("Meow! I need a destination URL first! 🐾");
            return;
        }
        if (!formData.uri) {
            setErrorMsg("Please generate or write a short URI code!");
            return;
        }

        setLoading(true);
        setErrorMsg(null);
        setResult(null);

        try {
            const payload: LinkPayload = {
                remoteUrl: formData.remoteUrl,
                uri: formData.uri,
                subdomain: formData.subdomain || undefined,
                privacy: formData.privacy,
                expiryDate: new Date(formData.expiryDate).getTime()
            };

            if (user && user.id) {
                payload.userId = user.id;
            }

            const response = await fetch(`${API_BASE}/api/v1/link/new`, {
                method: 'POST',
                headers: getAuthHeaders(), // Tu wstrzykujemy JWT
                body: JSON.stringify(payload)
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.error || `Database error ${response.status}`);
            }

            const finalLink = data.url || `${API_BASE.replace('api.', '')}/${formData.uri}`;
            setResult(finalLink);

        } catch (err: unknown) {
            if (err instanceof Error) setErrorMsg(err.message);
            else setErrorMsg("Something went wrong saving to DB!");
        } finally {
            setLoading(false);
        }
    };

    const copyToClipboard = (text: string) => {
        navigator.clipboard.writeText(text);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
    };

    return (
        <div className="max-w-[800px] mx-auto pt-10 px-4 flex flex-col items-center pb-20">
            {/* Header */}
            <header className="text-center mb-8 relative w-full flex flex-col items-center">
                <div className={`mb-4 px-4 py-2 rounded-full text-xs font-bold flex items-center gap-2 transition-colors ${user ? 'bg-pink-100 text-pink-600' : 'bg-gray-100 text-gray-400'}`}>
                    <UserIcon size={14} />
                    {user ? `Logged in as ${user.username}` : 'Guest Mode (Anonymous)'}
                </div>

                <h1 className="text-4xl sm:text-6xl font-black text-pink-500 mb-2 tracking-tighter flex items-center justify-center gap-2">
                    KittyURL <PawPrint className="w-8 h-8 sm:w-10 sm:h-10" fill="currentColor" />
                </h1>
                
            </header>

            {/* Error Display */}
            {errorMsg && (
                <div className="w-full mb-6 animate-in fade-in slide-in-from-top-2">
                    <div className="bg-red-50 border-2 border-red-200 p-4 rounded-2xl flex items-center gap-3 text-red-600 shadow-lg">
                        <AlertCircle size={20} />
                        <span className="font-bold text-sm flex-1">{errorMsg}</span>
                        <button onClick={() => setErrorMsg(null)}><X size={20} className="hover:scale-110 transition-transform" /></button>
                    </div>
                </div>
            )}

            {/* Success Result Card */}
            {result && (
                <div className="w-full mb-8 animate-in zoom-in-95 duration-500">
                    <div className="bg-gradient-to-r from-green-400 to-emerald-500 p-1 rounded-[2.5rem] shadow-2xl shadow-green-200">
                        <div className="bg-white rounded-[2.3rem] p-6 flex flex-col sm:flex-row items-center gap-4">
                            <div className="bg-green-100 p-3 rounded-full"><Check className="text-green-600 w-6 h-6" /></div>
                            <div className="flex-1 text-center sm:text-left overflow-hidden w-full">
                                <p className="text-[10px] font-black uppercase tracking-widest text-green-400 mb-1">Saved to Database!</p>
                                <p className="text-xl font-black text-gray-700 truncate">{result}</p>
                            </div>
                            <div className="flex gap-2">
                                <button onClick={() => copyToClipboard(result)} className="p-3 bg-gray-100 hover:bg-gray-200 rounded-xl transition-colors">
                                    {copied ? <Check size={20} className="text-green-600" /> : <Copy size={20} className="text-gray-600" />}
                                </button>
                                <a href={result} target="_blank" rel="noreferrer" className="p-3 bg-pink-500 hover:bg-pink-600 text-white rounded-xl transition-colors">
                                    <ExternalLink size={20} />
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Main Form */}
            <div className="w-full bg-white rounded-[2.5rem] shadow-2xl shadow-pink-200/50 p-6 sm:p-8 border-4 border-white">

                {/* 1. Destination URL */}
                <div className="mb-8">
                    <label className="flex items-center gap-2 text-[11px] font-black uppercase tracking-widest text-pink-400 mb-2 ml-1">
                        <Settings2 size={12} /> 1. Destination URL
                    </label>
                    <div className="relative group">
                        <input
                            type="url"
                            placeholder="https://very-long-link.com/..."
                            className="w-full p-4 bg-pink-50/30 border-2 border-pink-100 rounded-2xl outline-none focus:border-pink-400 focus:bg-white transition-all text-pink-600 font-medium pr-12"
                            value={formData.remoteUrl}
                            onChange={(e) => setFormData({ ...formData, remoteUrl: e.target.value })}
                        />
                        <Heart className="absolute right-4 top-1/2 -translate-y-1/2 text-pink-200 w-5 h-5 group-focus-within:text-pink-400 transition-colors" />
                    </div>
                </div>

                {/* 2. Short Code Generation */}
                <div className="mb-8 bg-pink-50/30 p-5 rounded-[2rem] border border-pink-100">
                    <label className="flex items-center gap-2 text-[11px] font-black uppercase tracking-widest text-pink-400 mb-3 ml-1">
                        <Sparkles size={12} /> 2. Generate Short Code (URI)
                    </label>

                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 mb-4">
                        <div className="bg-white p-2 rounded-xl border border-pink-100">
                            <label className="text-[9px] font-bold text-gray-400 uppercase block mb-1">Length</label>
                            <input type="number" min="3" max="32" className="w-full font-bold text-pink-500 outline-none text-sm"
                                value={genSettings.length} onChange={e => setGenSettings({ ...genSettings, length: +e.target.value })} />
                        </div>
                        <div className="bg-white p-2 rounded-xl border border-pink-100">
                            <label className="text-[9px] font-bold text-gray-400 uppercase block mb-1">Case</label>
                            <select
                                className="w-full font-bold text-pink-500 outline-none text-sm bg-transparent"
                                value={genSettings.case}
                                onChange={e => setGenSettings({ ...genSettings, case: e.target.value as CaseType })}
                            >
                                <option value="mixed">Mixed</option>
                                <option value="lower">Lower</option>
                                <option value="upper">Upper</option>
                            </select>
                        </div>
                        <button
                            onClick={() => handleGenerateUri('random')}
                            disabled={generatingUri}
                            className="col-span-2 sm:col-span-1 bg-white hover:bg-pink-100 border-2 border-pink-200 text-pink-500 rounded-xl font-bold text-xs flex flex-col items-center justify-center gap-1 transition-all active:scale-95 py-2"
                        >
                            <Hash size={16} />
                            {generatingUri ? '...' : 'Random'}
                        </button>
                        <button
                            onClick={() => handleGenerateUri('wordlist')}
                            disabled={generatingUri}
                            className="col-span-2 sm:col-span-1 bg-white hover:bg-pink-100 border-2 border-pink-200 text-pink-500 rounded-xl font-bold text-xs flex flex-col items-center justify-center gap-1 transition-all active:scale-95 py-2"
                        >
                            <BookOpen size={16} />
                            {generatingUri ? '...' : 'Sentence'}
                        </button>
                    </div>

                    <div className="relative">
                        <input
                            type="text"
                            placeholder="my-custom-uri"
                            className="w-full p-4 pl-12 bg-white border-2 border-pink-200 rounded-2xl outline-none focus:border-pink-500 transition-all text-pink-600 font-black text-lg shadow-inner"
                            value={formData.uri}
                            onChange={(e) => setFormData({ ...formData, uri: e.target.value })}
                        />
                        <div className="absolute left-4 top-1/2 -translate-y-1/2 text-pink-300 font-bold select-none">/</div>
                        {formData.uri && (
                            <div className="absolute right-4 top-1/2 -translate-y-1/2">
                                <Check size={18} className="text-green-500" />
                            </div>
                        )}
                    </div>
                </div>

                {/* 3. Database Settings */}
                <div className="mb-8 grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="bg-gray-50 p-4 rounded-2xl border border-gray-100">
                        <label className="flex items-center gap-2 text-[10px] font-black uppercase text-gray-400 mb-2"><Calendar size={14} /> Expiry Date</label>
                        <input type="date" className="w-full bg-white border border-gray-200 rounded-lg px-3 py-2 text-xs font-bold text-gray-600 outline-none focus:border-pink-400"
                            value={formData.expiryDate}
                            onChange={e => setFormData({ ...formData, expiryDate: e.target.value })} />
                    </div>

                    <label className="flex items-center justify-between bg-gray-50 p-4 rounded-2xl border border-gray-100 cursor-pointer hover:bg-pink-50 transition-colors">
                        <span className="flex items-center gap-2 text-[10px] font-black uppercase text-gray-400"><Shield size={14} /> Private Link</span>
                        <input type="checkbox" className="accent-pink-500 w-5 h-5" checked={formData.privacy}
                            onChange={e => setFormData({ ...formData, privacy: e.target.checked })} />
                    </label>

                    <label className="flex items-center justify-between bg-gray-50 p-4 rounded-2xl border border-gray-100 cursor-pointer hover:bg-pink-50 transition-colors sm:col-span-2">
                        <span className="flex items-center gap-2 text-[10px] font-black uppercase text-gray-400"><Globe size={14} /> Subdomain Support</span>
                        <input type="checkbox" className="accent-pink-500 w-5 h-5" checked={genSettings.withSubdomain}
                            onChange={e => {
                                setGenSettings({ ...genSettings, withSubdomain: e.target.checked });
                                setFormData({ ...formData, subdomain: e.target.checked ? 'true' : '' });
                            }} />
                    </label>
                </div>

                {/* 4. Submit Button */}
                <button
                    onClick={handleSubmitToDb}
                    disabled={loading}
                    className="w-full bg-pink-500 hover:bg-pink-600 text-white font-black py-5 rounded-[1.8rem] transition-all shadow-xl shadow-pink-200 active:scale-[0.98] text-xl flex items-center justify-center gap-3 disabled:opacity-50 disabled:grayscale"
                >
                    {loading ? (
                        <>Saving... <RefreshCw className="animate-spin" /></>
                    ) : (
                        <>Save to Database <Save className="w-6 h-6" /></>
                    )}
                </button>

            </div>

            <footer className="mt-12 text-center opacity-40">
                <Cat className="mx-auto text-pink-300 mb-2 w-10 h-10" />
                <p className="text-pink-300 font-black text-[10px] uppercase tracking-[0.2em]">
                    KittyURL Generator v2.0
                </p>
            </footer>
        </div>
    );
};