import { Head, Link, router, useForm } from "@inertiajs/react";
import AppLayout from "@/layouts/app-layout";
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import {
    Building2,
    Users,
    UserCheck,
    Package,
    ShoppingCart,
    FileText,
    CreditCard,
    MapPin,
    ShieldCheck,
    Calendar,
    Mail,
    Phone,
    ArrowLeft,
    CheckCircle2,
    Clock,
    Layers,
    Sparkles,
    Activity,
    Save,
    BadgeAlert,
} from "lucide-react";
import { StatChip } from "@/components/crm/global-card"; // Mengimpor komponen reusable StatChip

interface Plan {
    id: number;
    name: string;
    slug: string;
    monthly_price: number;
}
interface Company {
    id: number;
    nama: string;
    kode_perusahaan: string;
    email: string | null;
    telepon: string | null;
    alamat: string | null;
    status: string;
    subscription_status: string;
    subscription_expires_at: string | null;
    subscription_started_at: string | null;
    subscription_plan?: Plan | null;
    users_count: number;
    roles_count: number;
    teams_count: number;
    customers_count: number;
    products_count: number;
    orders_count: number;
    invoices_count: number;
    payments_count: number;
    visits_count: number;
}

const money = (value: number) =>
    new Intl.NumberFormat("id-ID", {
        style: "currency",
        currency: "IDR",
        maximumFractionDigits: 0,
    }).format(Number(value) || 0);

export default function CompanyShow({
    company,
    plans,
}: {
    company: Company;
    plans: Plan[];
}) {
    const companyForm = useForm({
        nama: company.nama,
        kode_perusahaan: company.kode_perusahaan,
        email: company.email || "",
        telepon: company.telepon || "",
        alamat: company.alamat || "",
    });
    const subscriptionForm = useForm({
        subscription_plan_id: company.subscription_plan?.id || "",
        subscription_status: company.subscription_status,
        subscription_expires_at: company.subscription_expires_at || "",
    });

    const saveCompany = (event: React.FormEvent) => {
        event.preventDefault();
        companyForm.put(`/platform/companies/${company.id}`);
    };
    const saveSubscription = (event: React.FormEvent) => {
        event.preventDefault();
        subscriptionForm.put(`/platform/companies/${company.id}/subscription`);
    };
    const setStatus = (status: string) =>
        router.put(`/platform/companies/${company.id}/status`, { status });

    // Badge status styling helpers
    const getStatusBadge = (status: string) => {
        switch (status) {
            case "active":
                return (
                    <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200 shadow-xs">
                        <CheckCircle2 className="w-3.5 h-3.5" /> Aktif
                    </span>
                );
            case "trial":
                return (
                    <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-amber-50 text-amber-700 border border-amber-200 shadow-xs">
                        <Clock className="w-3.5 h-3.5" /> Trial
                    </span>
                );
            case "suspended":
                return (
                    <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-rose-50 text-rose-700 border border-rose-200 shadow-xs">
                        <BadgeAlert className="w-3.5 h-3.5" /> Suspended
                    </span>
                );
            default:
                return (
                    <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-slate-100 text-slate-700 border border-slate-200 shadow-xs">
                        {status}
                    </span>
                );
        }
    };

    return (
        <AppLayout
            breadcrumbs={[
                { title: "Perusahaan", href: "/platform/companies" },
                {
                    title: company.nama,
                    href: `/platform/companies/${company.id}`,
                },
            ]}
        >
            <Head title={company.nama} />
            <div className="crm-page space-y-6 pb-10">
                {/* Header Section */}
                <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between bg-card p-6 rounded-2xl border shadow-sm relative overflow-hidden">
                    <div className="absolute top-0 right-0 w-96 h-96 bg-linear-to-br from-primary/5 via-transparent to-transparent rounded-full pointer-events-none -mr-20 -mt-20"></div>
                    <div className="flex items-start gap-4 z-10">
                        <div className="w-14 h-14 rounded-xl bg-primary/10 border border-primary/20 flex items-center justify-center text-primary shrink-0 shadow-inner">
                            <Building2 className="w-7 h-7" />
                        </div>
                        <div className="space-y-1">
                            <div className="flex flex-wrap items-center gap-3">
                                <h1 className="text-2xl md:text-3xl font-bold tracking-tight text-foreground">
                                    {company.nama}
                                </h1>
                                {getStatusBadge(company.status)}
                            </div>
                            <div className="flex items-center gap-2 text-sm text-muted-foreground font-medium">
                                <span className="font-mono bg-muted px-2 py-0.5 rounded text-xs border text-foreground">
                                    {company.kode_perusahaan}
                                </span>
                                <span>•</span>
                                <span className="flex items-center gap-1 text-primary font-medium">
                                    <Sparkles className="w-3.5 h-3.5" />
                                    {company.subscription_plan?.name ||
                                        "Tanpa Paket"}
                                </span>
                                <span>•</span>
                                <span>
                                    Expired:{" "}
                                    {company.subscription_expires_at ||
                                        "Selamanya"}
                                </span>
                            </div>
                        </div>
                    </div>
                    <div className="flex items-center gap-3 z-10">
                        <Button
                            asChild
                            variant="outline"
                            className="shadow-sm hover:bg-muted/80"
                        >
                            <Link
                                href="/platform/companies"
                                className="flex items-center gap-2"
                            >
                                <ArrowLeft className="w-4 h-4" /> Kembali
                            </Link>
                        </Button>
                    </div>
                </div>

                {/* Primary Metric Grid menggunakan StatChip Reusable */}
                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    <StatChip
                        icon={Users}
                        label="Total Users"
                        value={company.users_count}
                        tone="blue"
                        description="Pengguna aktif dalam tenant"
                        variant="compact"
                    />
                    <StatChip
                        icon={UserCheck}
                        label="Total Customers"
                        value={company.customers_count}
                        tone="emerald"
                        description="Basis data klien CRM"
                        variant="compact"
                    />
                    <StatChip
                        icon={Package}
                        label="Katalog Produk"
                        value={company.products_count}
                        tone="violet"
                        description="Produk & layanan aktif"
                        variant="compact"
                    />
                    <StatChip
                        icon={ShoppingCart}
                        label="Total Pesanan"
                        value={company.orders_count}
                        tone="orange"
                        description="Transaksi keseluruhan"
                        variant="compact"
                    />
                </div>

                {/* Main Forms Section */}
                <div className="grid gap-6 lg:grid-cols-2">
                    {/* Informasi Perusahaan */}
                    <Card className="border shadow-sm hover:shadow-md transition-shadow">
                        <CardHeader className="border-b bg-muted/20 pb-4">
                            <div className="flex items-center gap-2">
                                <Building2 className="w-5 h-5 text-primary" />
                                <div>
                                    <CardTitle className="text-base font-semibold">
                                        Informasi Perusahaan
                                    </CardTitle>
                                    <CardDescription className="text-xs">
                                        Kelola profil identitas dan kontak
                                        tenant
                                    </CardDescription>
                                </div>
                            </div>
                        </CardHeader>
                        <CardContent className="pt-6">
                            <form onSubmit={saveCompany} className="space-y-4">
                                <Field
                                    label="Nama Perusahaan"
                                    icon={
                                        <Building2 className="w-4 h-4 text-muted-foreground" />
                                    }
                                    value={companyForm.data.nama}
                                    onChange={(value) =>
                                        companyForm.setData("nama", value)
                                    }
                                    error={companyForm.errors.nama}
                                />
                                <Field
                                    label="Kode Perusahaan"
                                    icon={
                                        <ShieldCheck className="w-4 h-4 text-muted-foreground" />
                                    }
                                    value={companyForm.data.kode_perusahaan}
                                    onChange={(value) =>
                                        companyForm.setData(
                                            "kode_perusahaan",
                                            value,
                                        )
                                    }
                                    error={companyForm.errors.kode_perusahaan}
                                />
                                <Field
                                    label="Email Kontak"
                                    icon={
                                        <Mail className="w-4 h-4 text-muted-foreground" />
                                    }
                                    value={companyForm.data.email}
                                    onChange={(value) =>
                                        companyForm.setData("email", value)
                                    }
                                    error={companyForm.errors.email}
                                />
                                <Field
                                    label="Nomor Telepon"
                                    icon={
                                        <Phone className="w-4 h-4 text-muted-foreground" />
                                    }
                                    value={companyForm.data.telepon}
                                    onChange={(value) =>
                                        companyForm.setData("telepon", value)
                                    }
                                    error={companyForm.errors.telepon}
                                />
                                <div className="space-y-2">
                                    <Label className="flex items-center gap-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                                        <MapPin className="w-3.5 h-3.5 text-muted-foreground" />{" "}
                                        Alamat Lengkap
                                    </Label>
                                    <Textarea
                                        className="min-h-24 resize-none shadow-sm focus-visible:ring-primary"
                                        placeholder="Masukkan alamat lengkap perusahaan..."
                                        value={companyForm.data.alamat}
                                        onChange={(event) =>
                                            companyForm.setData(
                                                "alamat",
                                                event.target.value,
                                            )
                                        }
                                    />
                                </div>
                                <Button
                                    disabled={companyForm.processing}
                                    className="w-full sm:w-auto gap-2 shadow-sm"
                                >
                                    <Save className="w-4 h-4" /> Simpan
                                    Perubahan
                                </Button>
                            </form>
                        </CardContent>
                    </Card>

                    {/* Subscription Management */}
                    <Card className="border shadow-sm hover:shadow-md transition-shadow">
                        <CardHeader className="border-b bg-muted/20 pb-4">
                            <div className="flex items-center gap-2">
                                <Sparkles className="w-5 h-5 text-amber-500" />
                                <div>
                                    <CardTitle className="text-base font-semibold">
                                        Langganan & Paket
                                    </CardTitle>
                                    <CardDescription className="text-xs">
                                        Atur jenis paket layanan dan masa aktif
                                        tenant
                                    </CardDescription>
                                </div>
                            </div>
                        </CardHeader>
                        <CardContent className="pt-6">
                            <form
                                onSubmit={saveSubscription}
                                className="space-y-4"
                            >
                                <div className="space-y-2">
                                    <Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                                        Paket Langganan
                                    </Label>
                                    <Select
                                        value={String(
                                            subscriptionForm.data
                                                .subscription_plan_id,
                                        )}
                                        onValueChange={(value) =>
                                            subscriptionForm.setData(
                                                "subscription_plan_id",
                                                Number(value),
                                            )
                                        }
                                    >
                                        <SelectTrigger className="shadow-sm">
                                            <SelectValue placeholder="Pilih paket langganan" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {plans.map((plan) => (
                                                <SelectItem
                                                    key={plan.id}
                                                    value={String(plan.id)}
                                                >
                                                    <span className="font-medium">
                                                        {plan.name}
                                                    </span>{" "}
                                                    <span className="text-muted-foreground">
                                                        —{" "}
                                                        {money(
                                                            plan.monthly_price,
                                                        )}
                                                        /bulan
                                                    </span>
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                </div>
                                <div className="space-y-2">
                                    <Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                                        Status Subscription
                                    </Label>
                                    <Select
                                        value={
                                            subscriptionForm.data
                                                .subscription_status
                                        }
                                        onValueChange={(value) =>
                                            subscriptionForm.setData(
                                                "subscription_status",
                                                value,
                                            )
                                        }
                                    >
                                        <SelectTrigger className="shadow-sm">
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="trial">
                                                Trial
                                            </SelectItem>
                                            <SelectItem value="active">
                                                Active
                                            </SelectItem>
                                            <SelectItem value="past_due">
                                                Past Due
                                            </SelectItem>
                                            <SelectItem value="cancelled">
                                                Cancelled
                                            </SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                                <div className="space-y-2">
                                    <Label className="flex items-center gap-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                                        <Calendar className="w-3.5 h-3.5" />{" "}
                                        Tanggal Berakhir (Expired)
                                    </Label>
                                    <Input
                                        type="date"
                                        className="shadow-sm"
                                        value={
                                            subscriptionForm.data
                                                .subscription_expires_at
                                        }
                                        onChange={(event) =>
                                            subscriptionForm.setData(
                                                "subscription_expires_at",
                                                event.target.value,
                                            )
                                        }
                                    />
                                </div>
                                <div className="pt-2">
                                    <Button
                                        disabled={subscriptionForm.processing}
                                        className="w-full sm:w-auto gap-2 shadow-sm"
                                    >
                                        <Save className="w-4 h-4" /> Simpan
                                        Subscription
                                    </Button>
                                </div>
                            </form>
                        </CardContent>
                    </Card>
                </div>

                {/* Status Kontrol Tenant */}
                <Card className="border shadow-sm">
                    <CardHeader className="border-b bg-muted/20 pb-4">
                        <div className="flex items-center gap-2">
                            <Activity className="w-5 h-5 text-indigo-500" />
                            <div>
                                <CardTitle className="text-base font-semibold">
                                    Kontrol Status Tenant
                                </CardTitle>
                                <CardDescription className="text-xs">
                                    Ubah hak akses operasional perusahaan pada
                                    platform secara instan
                                </CardDescription>
                            </div>
                        </div>
                    </CardHeader>
                    <CardContent className="pt-6 flex flex-wrap gap-3">
                        <Button
                            variant={
                                company.status === "active"
                                    ? "default"
                                    : "outline"
                            }
                            className={`gap-2 shadow-sm ${company.status === "active" ? "bg-emerald-600 hover:bg-emerald-700" : ""}`}
                            onClick={() => setStatus("active")}
                        >
                            <CheckCircle2 className="w-4 h-4" /> Aktifkan Tenant
                        </Button>
                        <Button
                            variant={
                                company.status === "trial"
                                    ? "default"
                                    : "outline"
                            }
                            className={`gap-2 shadow-sm ${company.status === "trial" ? "bg-amber-600 hover:bg-amber-700" : ""}`}
                            onClick={() => setStatus("trial")}
                        >
                            <Clock className="w-4 h-4" /> Set Mode Trial
                        </Button>
                        <Button
                            variant={
                                company.status === "suspended"
                                    ? "destructive"
                                    : "outline"
                            }
                            className="gap-2 shadow-sm"
                            onClick={() => setStatus("suspended")}
                        >
                            <BadgeAlert className="w-4 h-4" /> Suspend Tenant
                        </Button>
                    </CardContent>
                </Card>

                {/* Ringkasan Data Operasional CRM menggunakan StatChip variant detailed */}
                <Card className="border shadow-sm">
                    <CardHeader className="border-b bg-muted/20 pb-4">
                        <div className="flex items-center gap-2">
                            <Layers className="w-5 h-5 text-blue-500" />
                            <div>
                                <CardTitle className="text-base font-semibold">
                                    Ringkasan Data & Aktivitas
                                </CardTitle>
                                <CardDescription className="text-xs">
                                    Metrik menyeluruh modul operasional di dalam
                                    ekosistem perusahaan
                                </CardDescription>
                            </div>
                        </div>
                    </CardHeader>
                    <CardContent className="pt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
                        <StatChip
                            icon={ShieldCheck}
                            label="Roles"
                            value={company.roles_count}
                            tone="blue"
                            description="Hak akses & peranan"
                            variant="detailed"
                        />
                        <StatChip
                            icon={Users}
                            label="Teams"
                            value={company.teams_count}
                            tone="emerald"
                            description="Grup divisi kerja"
                            variant="detailed"
                        />
                        <StatChip
                            icon={FileText}
                            label="Invoices"
                            value={company.invoices_count}
                            tone="violet"
                            description="Tagihan & penagihan"
                            variant="detailed"
                        />
                        <StatChip
                            icon={CreditCard}
                            label="Payments"
                            value={company.payments_count}
                            tone="orange"
                            description="Riwayat pembayaran"
                            variant="detailed"
                        />
                        <StatChip
                            icon={MapPin}
                            label="Visits"
                            value={company.visits_count}
                            tone="rose"
                            description="Kunjungan lapangan"
                            variant="detailed"
                        />
                    </CardContent>
                </Card>
            </div>
        </AppLayout>
    );
}

function Field({
    label,
    icon,
    value,
    onChange,
    error,
}: {
    label: string;
    icon?: React.ReactNode;
    value: string;
    onChange: (value: string) => void;
    error?: string;
}) {
    return (
        <div className="space-y-1.5">
            <Label className="flex items-center gap-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                {icon} {label}
            </Label>
            <Input
                value={value}
                className="shadow-sm focus-visible:ring-primary"
                onChange={(event) => onChange(event.target.value)}
            />
            {error && (
                <p className="text-xs text-destructive font-medium">{error}</p>
            )}
        </div>
    );
}
