import { Head, useForm } from "@inertiajs/react";
import AppLayout from "@/layouts/app-layout";
import { Button } from "@/components/ui/button";
import {
    Card,
    CardContent,
    CardHeader,
    CardTitle,
    CardDescription,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
    Building2,
    Mail,
    Phone,
    MapPin,
    CreditCard,
    ShieldCheck,
    Save,
    Loader2,
    QrCode,
    Sparkles,
    Globe,
} from "lucide-react";
import { StatChip } from "@/components/crm/global-card";

interface Company {
    id: number;
    nama: string;
    kode_perusahaan: string;
    email?: string;
    telepon?: string;
    alamat?: string;
    status: string;
    subscription_status?: string;
    subscription_expires_at?: string;
    settings?: { visit_min_interval_days?: number };
}

// Helper untuk format tanggal Indonesia
const formatDate = (dateString?: string) => {
    if (!dateString) return "Unlimited License";

    const date = new Date(dateString);
    if (isNaN(date.getTime())) return dateString;

    return new Intl.DateTimeFormat("id-ID", {
        day: "numeric",
        month: "long",
        year: "numeric",
    }).format(date);
};

export default function CompanySettings({ company }: { company: Company }) {
    const form = useForm({
        nama: company.nama ?? "",
        kode_perusahaan: company.kode_perusahaan ?? "",
        email: company.email ?? "",
        telepon: company.telepon ?? "",
        alamat: company.alamat ?? "",
        visit_min_interval_days: company.settings?.visit_min_interval_days ?? 3,
    });

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        form.put("/settings/company");
    };

    return (
        <AppLayout
            breadcrumbs={[
                { title: "Pengaturan Perusahaan", href: "/settings/company" },
            ]}
        >
            <Head title="Pengaturan Profil Perusahaan" />

            <div className="crm-page space-y-6 pb-12">
                {/* Header Section */}
                <div className="flex flex-col justify-between gap-4 border-b border-slate-200/80 pb-5 md:flex-row md:items-center dark:border-slate-800">
                    <div>
                        <div className="mb-1 flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-indigo-600 dark:text-indigo-400">
                            <Building2 className="size-4" /> Enterprise
                            Organization Settings
                        </div>
                        <h1 className="text-2xl font-extrabold tracking-tight text-slate-900 dark:text-slate-50">
                            Profil Perusahaan
                        </h1>
                        <p className="text-sm text-slate-500 dark:text-slate-400">
                            Kelola identitas utama bisnis, info kontak
                            operasional, dan parameter langganan CRM Anda.
                        </p>
                    </div>
                </div>

                {/* Subscription & KPI Banner */}
                <div className="grid gap-4 sm:grid-cols-3">
                    <StatChip
                        icon={Globe}
                        label="Identitas Organisasi"
                        value={company.nama || "Belum Diset"}
                        tone="cyan"
                        variant="compact"
                        description={`Kode: ${company.kode_perusahaan || "-"}`}
                    />

                    <StatChip
                        icon={ShieldCheck}
                        label="Status Akun Perusahaan"
                        value={
                            company.status
                                ? company.status.toUpperCase()
                                : "ACTIVE"
                        }
                        tone="emerald"
                        variant="compact"
                        description="Sistem berjalan terverifikasi"
                    />

                    <StatChip
                        icon={CreditCard}
                        label="Paket Langganan"
                        value={company.subscription_status || "Enterprise Tier"}
                        tone="violet"
                        variant="compact"
                        description={`Berakhir: ${formatDate(company.subscription_expires_at)}`}
                    />
                </div>

                {/* Form Settings Section */}
                <Card className="rounded-2xl border-slate-200/80 bg-white shadow-2xs dark:border-slate-800 dark:bg-slate-900">
                    <CardHeader className="border-b border-slate-100 pb-4 dark:border-slate-800">
                        <div className="flex items-center gap-2.5">
                            <div className="rounded-xl bg-indigo-50 p-2.5 text-indigo-600 dark:bg-indigo-950/50 dark:text-indigo-400">
                                <Building2 className="size-5" />
                            </div>
                            <div>
                                <CardTitle className="text-base font-bold text-slate-900 dark:text-slate-100">
                                    Informasi Legal & Kontak Perusahaan
                                </CardTitle>
                                <CardDescription className="text-xs">
                                    Perbarui rincian resmi yang akan ditampilkan
                                    pada faktur, penawaran, dan header laporan.
                                </CardDescription>
                            </div>
                        </div>
                    </CardHeader>

                    <CardContent className="pt-6">
                        <form onSubmit={submit} className="space-y-6">
                            {/* Section 1: Basic Information */}
                            <div className="space-y-4">
                                <h3 className="text-xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">
                                    1. Identitas Utama
                                </h3>
                                <div className="grid gap-5 md:grid-cols-2">
                                    <div className="space-y-1.5">
                                        <Label className="text-xs font-semibold text-slate-700 dark:text-slate-300">
                                            Nama Perusahaan{" "}
                                            <span className="text-rose-500">
                                                *
                                            </span>
                                        </Label>
                                        <div className="relative">
                                            <Building2 className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-slate-400" />
                                            <Input
                                                className="rounded-xl border-slate-200 dark:border-slate-800 pl-9 focus-visible:ring-indigo-500"
                                                placeholder="PT Samudra Indonesia Tbk"
                                                value={form.data.nama}
                                                onChange={(e) =>
                                                    form.setData(
                                                        "nama",
                                                        e.target.value,
                                                    )
                                                }
                                            />
                                        </div>
                                        {form.errors.nama && (
                                            <p className="text-xs font-medium text-rose-500">
                                                {form.errors.nama}
                                            </p>
                                        )}
                                    </div>

                                    <div className="space-y-1.5">
                                        <Label className="text-xs font-semibold text-slate-700 dark:text-slate-300">
                                            Kode Perusahaan{" "}
                                            <span className="text-rose-500">
                                                *
                                            </span>
                                        </Label>
                                        <div className="relative">
                                            <QrCode className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-slate-400" />
                                            <Input
                                                className="rounded-xl border-slate-200 dark:border-slate-800 pl-9 font-mono text-xs uppercase focus-visible:ring-indigo-500"
                                                placeholder="CMP-2026-001"
                                                value={
                                                    form.data.kode_perusahaan
                                                }
                                                onChange={(e) =>
                                                    form.setData(
                                                        "kode_perusahaan",
                                                        e.target.value,
                                                    )
                                                }
                                            />
                                        </div>
                                        {form.errors.kode_perusahaan && (
                                            <p className="text-xs font-medium text-rose-500">
                                                {form.errors.kode_perusahaan}
                                            </p>
                                        )}
                                    </div>
                                </div>
                            </div>

                            {/* Section 2: Contact Information */}
                            <div className="space-y-4 pt-2">
                                <h3 className="text-xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">
                                    2. Saluran Komunikasi
                                </h3>
                                <div className="grid gap-5 md:grid-cols-2">
                                    <div className="space-y-1.5">
                                        <Label className="text-xs font-semibold text-slate-700 dark:text-slate-300">
                                            Email Resmi Perusahaan
                                        </Label>
                                        <div className="relative">
                                            <Mail className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-slate-400" />
                                            <Input
                                                type="email"
                                                className="rounded-xl border-slate-200 dark:border-slate-800 pl-9 focus-visible:ring-indigo-500"
                                                placeholder="corporate@company.com"
                                                value={form.data.email}
                                                onChange={(e) =>
                                                    form.setData(
                                                        "email",
                                                        e.target.value,
                                                    )
                                                }
                                            />
                                        </div>
                                        {form.errors.email && (
                                            <p className="text-xs font-medium text-rose-500">
                                                {form.errors.email}
                                            </p>
                                        )}
                                    </div>

                                    <div className="space-y-1.5">
                                        <Label className="text-xs font-semibold text-slate-700 dark:text-slate-300">
                                            Nomor Telepon Kantor
                                        </Label>
                                        <div className="relative">
                                            <Phone className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-slate-400" />
                                            <Input
                                                className="rounded-xl border-slate-200 dark:border-slate-800 pl-9 focus-visible:ring-indigo-500"
                                                placeholder="+62 21 555 0192"
                                                value={form.data.telepon}
                                                onChange={(e) =>
                                                    form.setData(
                                                        "telepon",
                                                        e.target.value,
                                                    )
                                                }
                                            />
                                        </div>
                                        {form.errors.telepon && (
                                            <p className="text-xs font-medium text-rose-500">
                                                {form.errors.telepon}
                                            </p>
                                        )}
                                    </div>
                                </div>
                            </div>

                            {/* Section 3: Address */}
                            <div className="space-y-4 pt-2">
                                <h3 className="text-xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">
                                    3. Alamat Domisili
                                </h3>
                                <div className="space-y-1.5">
                                    <Label className="text-xs font-semibold text-slate-700 dark:text-slate-300">
                                        Alamat Lengkap Perusahaan
                                    </Label>
                                    <div className="relative">
                                        <MapPin className="absolute left-3 top-3 size-4 text-slate-400" />
                                        <Textarea
                                            rows={3}
                                            className="min-h-25 rounded-xl border-slate-200 dark:border-slate-800 pl-9 focus-visible:ring-indigo-500"
                                            placeholder="Gedung Cyber 2, Lt. 18, Jl. H.R. Rasuna Said, Kuningan, Jakarta Selatan, 12950"
                                            value={form.data.alamat}
                                            onChange={(e) =>
                                                form.setData(
                                                    "alamat",
                                                    e.target.value,
                                                )
                                            }
                                        />
                                    </div>
                                    {form.errors.alamat && (
                                        <p className="text-xs font-medium text-rose-500">
                                            {form.errors.alamat}
                                        </p>
                                    )}
                                </div>
                            </div>

                            {/* Section 4: Visit Rules */}
                            <div className="space-y-4 border-t border-slate-100 pt-6 dark:border-slate-800">
                                <div>
                                    <h3 className="text-xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">
                                        4. Aturan Kunjungan Sales
                                    </h3>
                                    <p className="mt-1 text-xs text-slate-500 dark:text-slate-400">
                                        Menentukan jarak minimum kunjungan
                                        kembali ke outlet yang sama.
                                    </p>
                                </div>
                                <div className="grid gap-5 md:grid-cols-2">
                                    <div className="space-y-1.5">
                                        <Label className="text-xs font-semibold text-slate-700 dark:text-slate-300">
                                            Minimal Jarak Kunjungan (Hari)
                                        </Label>
                                        <Input
                                            type="number"
                                            min={3}
                                            max={365}
                                            className="rounded-xl border-slate-200 dark:border-slate-800 focus-visible:ring-indigo-500"
                                            value={
                                                form.data
                                                    .visit_min_interval_days
                                            }
                                            onChange={(e) =>
                                                form.setData(
                                                    "visit_min_interval_days",
                                                    e.target.value === ""
                                                        ? 3
                                                        : Math.max(
                                                              3,
                                                              Number(
                                                                  e.target
                                                                      .value,
                                                              ),
                                                          ),
                                                )
                                            }
                                        />
                                        <p className="text-[11px] text-slate-500 dark:text-slate-400">
                                            Minimum 3 hari. Contoh: kunjungan 20
                                            September dapat dijadwalkan kembali
                                            mulai 23 September.
                                        </p>
                                        {form.errors
                                            .visit_min_interval_days && (
                                            <p className="text-xs font-medium text-rose-500">
                                                {
                                                    form.errors
                                                        .visit_min_interval_days
                                                }
                                            </p>
                                        )}
                                    </div>
                                </div>
                            </div>

                            {/* Form Action Footer */}
                            <div className="flex flex-col gap-4 border-t border-slate-100 pt-5 sm:flex-row sm:items-center sm:justify-between dark:border-slate-800">
                                <div className="flex items-center gap-2 text-xs text-slate-500 dark:text-slate-400">
                                    <Sparkles className="size-4 text-amber-500" />
                                    <span>
                                        Perubahan akan langsung terenkripsi dan
                                        diperbarui secara global.
                                    </span>
                                </div>

                                <Button
                                    type="submit"
                                    disabled={form.processing}
                                    className="cursor-pointer rounded-xl bg-indigo-600 font-semibold text-white shadow-md transition-all hover:bg-indigo-700 hover:shadow-indigo-500/20 disabled:opacity-50"
                                >
                                    {form.processing ? (
                                        <>
                                            <Loader2 className="mr-2 size-4 animate-spin" />{" "}
                                            Menyimpan...
                                        </>
                                    ) : (
                                        <>
                                            <Save className="mr-2 size-4" />{" "}
                                            Simpan Perubahan
                                        </>
                                    )}
                                </Button>
                            </div>
                        </form>
                    </CardContent>
                </Card>
            </div>
        </AppLayout>
    );
}
