"use client";

import { API_BASE_URL, getAuthHeaders } from "@/lib/api";
import React, { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { AlertCircle, Loader2, Save, Building2, Globe, Mail, Phone, MapPin, Palette, Check, ImagePlus, X } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { setCompanyLogoCache } from "@/hooks/useCompanyLogo";

const BRAND_COLORS = [
    { name: "Royal Indigo", value: "#4f46e5", oklch: "oklch(0.55 0.2 264)" },
    { name: "Ocean Teal", value: "#0891b2", oklch: "oklch(0.6 0.18 200)" },
    { name: "Emerald Green", value: "#059669", oklch: "oklch(0.6 0.18 165)" },
    { name: "Crimson Red", value: "#dc2626", oklch: "oklch(0.55 0.22 25)" },
    { name: "Amber Gold", value: "#d97706", oklch: "oklch(0.65 0.2 75)" },
];

export default function SettingsPage() {
    const [company, setCompany] = useState<any>(null);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const logoInputRef = React.useRef<HTMLInputElement>(null);

    useEffect(() => {
        async function fetchCompany() {
            try {
                const res = await fetch(`${API_BASE_URL}/companies/`, { headers: getAuthHeaders() });
                if (res.ok) {
                    const data = await res.json();
                    const list = data.results || data;
                    if (list.length > 0) {
                        const c = list[0];
                        setCompany(c);
                        // Apply saved brand color on load
                        const saved = c.brand_colors?.primary;
                        if (saved) applyBrandColor(saved);
                    }
                }
            } catch (err) {
                console.error("Failed to load settings:", err);
            } finally {
                setLoading(false);
            }
        }
        fetchCompany();
    }, []);

    function applyBrandColor(hex: string) {
        // Find if it matches a preset, and use the accurate oklch value
        const preset = BRAND_COLORS.find(c => c.value === hex);
        const oklchValue = preset ? preset.oklch : hexToOklch(hex);
        document.documentElement.style.setProperty("--primary", oklchValue);
        document.documentElement.style.setProperty("--ring", oklchValue);
        document.documentElement.style.setProperty("--sidebar-primary", oklchValue);
    }

    // Simple hex -> oklch approximation for non-preset colors
    function hexToOklch(hex: string): string {
        // fallback to indigo if parsing fails
        try {
            const r = parseInt(hex.slice(1, 3), 16) / 255;
            const g = parseInt(hex.slice(3, 5), 16) / 255;
            const b = parseInt(hex.slice(5, 7), 16) / 255;
            const l = Math.sqrt(0.299 * r * r + 0.587 * g * g + 0.114 * b * b);
            return `oklch(${(l * 0.7 + 0.2).toFixed(2)} 0.2 264)`;
        } catch {
            return "oklch(0.55 0.2 264)";
        }
    }

    const handleSave = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!company) return;
        setSaving(true);
        try {
            // Build FormData so Django's ImageField receives a real file blob
            const formData = new FormData();

            // Append plain text fields
            if (company.name !== undefined) formData.append("name", company.name ?? "");
            if (company.contact_email !== undefined) formData.append("contact_email", company.contact_email ?? "");
            if (company.contact_phone !== undefined) formData.append("contact_phone", company.contact_phone ?? "");
            if (company.address !== undefined) formData.append("address", company.address ?? "");
            if (company.website !== undefined) formData.append("website", company.website ?? "");
            if (company.brand_colors !== undefined) formData.append("brand_colors", JSON.stringify(company.brand_colors));

            // Logo handling:
            // - data: URL  → new file picked → convert to Blob and upload
            // - ""         → user cleared it → send empty to remove on server
            // - http/https → unchanged server URL → skip entirely (ImageField rejects URL strings)
            if (company.logo && company.logo.startsWith("data:")) {
                // Convert base64 → Blob → File
                const [meta, b64] = company.logo.split(",");
                const mime = meta.match(/:(.*?);/)?.[1] || "image/webp";
                const binary = atob(b64);
                const bytes = new Uint8Array(binary.length);
                for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
                const blob = new Blob([bytes], { type: mime });
                formData.append("logo", blob, "logo.webp");
            } else if (company.logo === "") {
                // User explicitly removed the logo — clear it on the server
                formData.append("logo", "");
            }
            // else: existing server URL unchanged — don't include in FormData at all

            // Don't set Content-Type — browser sets it with the correct multipart boundary
            const { "Content-Type": _ct, ...authHeaders } = getAuthHeaders() as Record<string, string>;
            const res = await fetch(`${API_BASE_URL}/companies/${company.id}/`, {
                method: "PATCH",
                headers: authHeaders,
                body: formData,
            });

            if (res.ok) {
                const updated = await res.json();
                // Update local state with the real URL returned by the server
                setCompany({ ...company, logo: updated.logo || company.logo });
                const finalLogo = updated.logo || company.logo || "";
                setCompanyLogoCache(finalLogo);
                alert("Organization settings updated successfully");
            } else {
                const err = await res.json();
                alert(`Update failed: ${JSON.stringify(err)}`);
            }
        } catch (err) {
            console.error(err);
            alert("Network error saving settings");
        } finally {
            setSaving(false);
        }
    };

    if (loading) return <div className="p-12 text-center animate-pulse text-muted-foreground font-black text-lg uppercase tracking-widest">Loading Core Engine Settings...</div>;

    if (!company) return (
        <div className="p-12 text-center">
            <h2 className="text-xl font-black text-foreground uppercase tracking-widest">No Company Profile Linked</h2>
            <p className="text-muted-foreground max-w-md mx-auto mt-4 font-medium">
                Your user account is not associated with a company profile yet. Please contact a super-admin to initialize your organization data.
            </p>
        </div>
    );

    return (
        <div className="flex-1 space-y-6 pb-12">
            <div>
                <h2 className="text-4xl font-black tracking-tight text-foreground bg-clip-text text-transparent bg-gradient-to-r from-primary to-emerald-600 dark:from-primary dark:to-emerald-400">Organization Profile</h2>
                <p className="text-muted-foreground mt-1 text-sm font-medium">
                    Configure your brand identity, contact channels, and geographical registration.
                </p>
            </div>

            <form onSubmit={handleSave} className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="md:col-span-2 space-y-6">
                    <Card className="rounded-2xl shadow-card border-none bg-card overflow-hidden">
                        <CardHeader className="bg-muted/10 border-b border-border/10">
                            <CardTitle className="text-lg font-bold flex items-center gap-2">
                                <Building2 className="w-5 h-5 text-primary" /> Identity & Branding
                            </CardTitle>
                            <CardDescription>Primary identification details for receipts and legal documents.</CardDescription>
                        </CardHeader>
                        <CardContent className="pt-6 space-y-4">
                            <div className="space-y-2">
                                <Label>Legal Entity Name</Label>
                                <Input
                                    value={company.name || ""}
                                    onChange={e => setCompany({ ...company, name: e.target.value })}
                                    className="font-bold text-foreground bg-muted/20"
                                />
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label className="flex items-center gap-2"><ImagePlus className="w-3.5 h-3.5" /> Organization Logo</Label>
                                    <div className="flex items-center gap-4">
                                        {/* Preview */}
                                        <div className="w-16 h-16 rounded-xl border border-border/20 bg-muted/10 flex items-center justify-center overflow-hidden flex-shrink-0">
                                            {company.logo
                                                ? <img src={company.logo} alt="Logo" className="w-full h-full object-contain" />
                                                : <span className="text-muted-foreground text-xs font-medium text-center leading-tight px-1">No Logo</span>
                                            }
                                        </div>
                                        <div className="flex-1 space-y-2">
                                            {/* Hidden file input */}
                                            <input
                                                ref={logoInputRef}
                                                type="file"
                                                accept="image/*"
                                                className="hidden"
                                                onChange={async (e) => {
                                                    const file = e.target.files?.[0];
                                                    if (!file) return;
                                                    // Compress via canvas
                                                    const MAX = 200;
                                                    const bitmap = await createImageBitmap(file);
                                                    const scale = Math.min(MAX / bitmap.width, MAX / bitmap.height, 1);
                                                    const w = Math.round(bitmap.width * scale);
                                                    const h = Math.round(bitmap.height * scale);
                                                    const canvas = document.createElement("canvas");
                                                    canvas.width = w; canvas.height = h;
                                                    canvas.getContext("2d")!.drawImage(bitmap, 0, 0, w, h);
                                                    const dataUrl = canvas.toDataURL("image/webp", 0.85);
                                                    setCompany({ ...company, logo: dataUrl });
                                                    // Reset so same file can be re-selected
                                                    e.target.value = "";
                                                }}
                                            />
                                            <Button
                                                type="button"
                                                variant="outline"
                                                className="w-full h-9 rounded-xl text-xs font-bold"
                                                onClick={() => logoInputRef.current?.click()}
                                            >
                                                <ImagePlus className="w-3.5 h-3.5 mr-2" />
                                                {company.logo ? "Replace Logo" : "Upload Logo"}
                                            </Button>
                                            {company.logo && (
                                                <Button
                                                    type="button"
                                                    variant="ghost"
                                                    className="w-full h-8 rounded-xl text-xs font-bold text-destructive hover:text-destructive hover:bg-destructive/10"
                                                    onClick={() => setCompany({ ...company, logo: "" })}
                                                >
                                                    <X className="w-3 h-3 mr-1" /> Remove Logo
                                                </Button>
                                            )}
                                        </div>
                                    </div>
                                    <p className="text-[10px] text-slate-400 italic">Image is compressed to 200×200px and stored locally. Appears in the header and on all receipts.</p>
                                </div>
                                <div className="space-y-3">
                                    <Label className="flex items-center gap-2"><Palette className="w-3.5 h-3.5" /> Primary Brand Color</Label>
                                    <div className="grid grid-cols-5 gap-3">
                                        {BRAND_COLORS.map(color => {
                                            const isSelected = (company.brand_colors?.primary || "#4f46e5") === color.value;
                                            return (
                                                <button
                                                    key={color.value}
                                                    type="button"
                                                    title={color.name}
                                                    onClick={() => {
                                                        const updated = { ...company, brand_colors: { ...(company.brand_colors || {}), primary: color.value } };
                                                        setCompany(updated);
                                                        applyBrandColor(color.value);
                                                    }}
                                                    className={`relative w-full aspect-square rounded-xl border-2 transition-all duration-200 hover:scale-110 active:scale-95 shadow-md ${isSelected ? "border-foreground scale-105 shadow-lg" : "border-transparent"
                                                        }`}
                                                    style={{ backgroundColor: color.value }}
                                                >
                                                    {isSelected && (
                                                        <Check className="absolute inset-0 m-auto w-5 h-5 text-white drop-shadow" />
                                                    )}
                                                </button>
                                            );
                                        })}
                                    </div>
                                    <p className="text-[10px] text-muted-foreground italic">
                                        {BRAND_COLORS.find(c => c.value === (company.brand_colors?.primary || "#4f46e5"))?.name || "Custom"} — applies immediately across the entire system.
                                    </p>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    <Card className="rounded-2xl shadow-card border-none bg-card overflow-hidden">
                        <CardHeader className="bg-muted/10 border-b border-border/10">
                            <CardTitle className="text-lg font-bold flex items-center gap-2">
                                <Globe className="w-5 h-5 text-emerald-600" /> Communication Channels
                            </CardTitle>
                            <CardDescription>Public-facing contact information for customers.</CardDescription>
                        </CardHeader>
                        <CardContent className="pt-6 space-y-4">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label className="flex items-center gap-2"><Mail className="w-3.5 h-3.5" /> Support Email</Label>
                                    <Input
                                        type="email"
                                        value={company.contact_email || ""}
                                        onChange={e => setCompany({ ...company, contact_email: e.target.value })}
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label className="flex items-center gap-2"><Phone className="w-3.5 h-3.5" /> Official Phone</Label>
                                    <Input
                                        value={company.contact_phone || ""}
                                        onChange={e => setCompany({ ...company, contact_phone: e.target.value })}
                                    />
                                </div>
                            </div>
                            <div className="space-y-2">
                                <Label className="flex items-center gap-2"><MapPin className="w-3.5 h-3.5" /> Physical Headquarters Address</Label>
                                <Textarea
                                    value={company.address || ""}
                                    onChange={e => setCompany({ ...company, address: e.target.value })}
                                    className="min-h-[100px]"
                                />
                            </div>
                        </CardContent>
                    </Card>
                </div>

                <div className="space-y-6">
                    <Card className="rounded-2xl shadow-card border-none bg-primary text-primary-foreground overflow-hidden">
                        <CardHeader className="pb-2 border-b border-primary-foreground/10 bg-black/5">
                            <CardTitle className="text-primary-foreground/80 uppercase text-[10px] font-black tracking-widest">Live Metadata</CardTitle>
                        </CardHeader>
                        <CardContent className="pt-6">
                            <div className="space-y-3 text-sm">
                                <div className="flex justify-between items-center">
                                    <span className="opacity-70 font-medium">Org ID:</span>
                                    <span className="font-mono font-bold tracking-tighter">#{company.id}</span>
                                </div>
                                <div className="flex justify-between items-center">
                                    <span className="opacity-70 font-medium">System Status:</span>
                                    <Badge className="bg-emerald-500 text-white border-none font-bold text-[10px]">ACTIVE</Badge>
                                </div>
                                <div className="flex justify-between items-center pt-3 border-t border-primary-foreground/10">
                                    <span className="opacity-70 font-medium">Registered:</span>
                                    <span className="font-bold">{new Date(company.created_at).toLocaleDateString()}</span>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    <Button type="submit" disabled={saving} className="w-full h-14 bg-emerald-600 hover:bg-emerald-700 text-white shadow-lg shadow-emerald-500/20 rounded-2xl text-lg font-black transition-all active:scale-95">
                        {saving ? <Loader2 className="w-5 h-5 animate-spin mr-2" /> : <Save className="w-5 h-5 mr-2" />} Save System Config
                    </Button>

                    <div className="p-5 rounded-2xl bg-muted/20 border border-border/10">
                        <h4 className="font-black text-foreground text-xs mb-2 uppercase tracking-tight flex items-center gap-2">
                            <AlertCircle className="w-4 h-4 text-amber-500" /> Security Protocol
                        </h4>
                        <p className="text-[11px] text-muted-foreground font-medium leading-relaxed">
                            Changes made to the Legal Entity Name or Address will propagate immediately across all system-generated receipts and active contracts.
                        </p>
                    </div>
                </div>
            </form>
        </div>
    );
}
