import { useEffect } from "react";
import { useForm } from "@inertiajs/react";
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";

type Option = { id: number; name: string };
type AreaOption = { id: number; code?: string; name: string };

type Customer = {
    id: number;
    code?: string;
    name: string;
    phone?: string;
    status: string;
    category?: Option;
    team?: Option;
    sales?: Option;
    area?: { id: number; name: string } | null;
};

interface CustomerFormDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    customer?: Customer | null;
    categories: Option[];
    salesUsers: Option[];
    areas: AreaOption[];
}

export function CustomerFormDialog({
    open,
    onOpenChange,
    customer,
    categories,
    salesUsers,
    areas,
}: CustomerFormDialogProps) {
    const isEdit = Boolean(customer);

    const { data, setData, post, put, processing, errors, reset } = useForm({
        name: "",
        code: "",
        phone: "",
        status: "active",
        category_id: "",
        sales_id: "",
        area_id: "",
    });

    useEffect(() => {
        if (customer) {
            setData({
                name: customer.name || "",
                code: customer.code || "",
                phone: customer.phone || "",
                status: customer.status || "active",
                category_id: customer.category?.id
                    ? String(customer.category.id)
                    : "",
                sales_id: customer.sales?.id ? String(customer.sales.id) : "",
                area_id: customer.area?.id ? String(customer.area.id) : "",
            });
        } else {
            reset();
        }
    }, [customer, open]);

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        if (isEdit && customer) {
            put(`/crm/customers/${customer.id}`, {
                onSuccess: () => onOpenChange(false),
            });
        } else {
            post("/crm/customers", {
                onSuccess: () => onOpenChange(false),
            });
        }
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-lg rounded-2xl">
                <DialogHeader>
                    <DialogTitle className="text-xl font-bold text-foreground">
                        {isEdit ? "Edit Customer" : "Tambah Customer"}
                    </DialogTitle>
                </DialogHeader>

                <form onSubmit={submit} className="space-y-4 py-2">
                    <div className="space-y-1">
                        <Label htmlFor="name">Nama Customer *</Label>
                        <Input
                            id="name"
                            value={data.name}
                            onChange={(e) => setData("name", e.target.value)}
                            placeholder="PT Mitra Jaya / Ahmad"
                            className="rounded-xl"
                        />
                        {errors.name && (
                            <p className="text-xs text-red-500">
                                {errors.name}
                            </p>
                        )}
                    </div>

                    <div className="grid grid-cols-2 gap-3">
                        <div className="space-y-1">
                            <Label htmlFor="code">Kode</Label>
                            <Input
                                id="code"
                                value={data.code}
                                onChange={(e) =>
                                    setData("code", e.target.value)
                                }
                                placeholder="CUST-001"
                                className="rounded-xl"
                            />
                        </div>
                        <div className="space-y-1">
                            <Label htmlFor="phone">Telepon</Label>
                            <Input
                                id="phone"
                                value={data.phone}
                                onChange={(e) =>
                                    setData("phone", e.target.value)
                                }
                                placeholder="08123456789"
                                className="rounded-xl"
                            />
                        </div>
                    </div>

                    <div className="grid grid-cols-2 gap-3">
                        <div className="space-y-1">
                            <Label>Kategori</Label>
                            <Select
                                value={data.category_id}
                                onValueChange={(v) => setData("category_id", v)}
                            >
                                <SelectTrigger className="rounded-xl">
                                    <SelectValue placeholder="Pilih Kategori" />
                                </SelectTrigger>
                                <SelectContent>
                                    {categories.map((c) => (
                                        <SelectItem
                                            key={c.id}
                                            value={String(c.id)}
                                        >
                                            {c.name}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>

                        <div className="space-y-1">
                            <Label>Status</Label>
                            <Select
                                value={data.status}
                                onValueChange={(v) => setData("status", v)}
                            >
                                <SelectTrigger className="rounded-xl">
                                    <SelectValue placeholder="Pilih Status" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="active">
                                        Aktif
                                    </SelectItem>
                                    <SelectItem value="inactive">
                                        Tidak Aktif
                                    </SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                    </div>

                    <div className="grid grid-cols-2 gap-3">
                        <div className="space-y-1">
                            <Label>Area</Label>
                            <Select
                                value={data.area_id}
                                onValueChange={(v) => setData("area_id", v)}
                            >
                                <SelectTrigger className="rounded-xl">
                                    <SelectValue placeholder="Pilih Area" />
                                </SelectTrigger>
                                <SelectContent>
                                    {areas.map((a) => (
                                        <SelectItem
                                            key={a.id}
                                            value={String(a.id)}
                                        >
                                            {a.code
                                                ? `${a.code} — ${a.name}`
                                                : a.name}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>

                        <div className="space-y-1">
                            <Label>Sales</Label>
                            <Select
                                value={data.sales_id}
                                onValueChange={(v) => setData("sales_id", v)}
                            >
                                <SelectTrigger className="rounded-xl">
                                    <SelectValue placeholder="Pilih Sales" />
                                </SelectTrigger>
                                <SelectContent>
                                    {salesUsers.map((s) => (
                                        <SelectItem
                                            key={s.id}
                                            value={String(s.id)}
                                        >
                                            {s.name}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                    </div>

                    <DialogFooter className="mt-6 gap-2">
                        <Button
                            type="button"
                            variant="outline"
                            onClick={() => onOpenChange(false)}
                            className="rounded-xl"
                        >
                            Batal
                        </Button>
                        <Button
                            type="submit"
                            disabled={processing}
                            className="rounded-xl bg-blue-600 font-semibold hover:bg-blue-700"
                        >
                            {processing
                                ? "Menyimpan..."
                                : isEdit
                                  ? "Update"
                                  : "Simpan"}
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}
