"use client";

import { useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { handleUpdateChartAccount } from "@/lib/actions";
import type { ChartOfAccount } from "@/lib/types";
import { useToast } from "@/hooks/use-toast";
import { cn } from "@/lib/utils";
import { Check, ChevronsUpDown } from "lucide-react";

const ROOT_OPTION = "__root__";

type Props = {
  account: ChartOfAccount;
  accounts: ChartOfAccount[];
};

export default function EditAccountDialog({ account, accounts }: Props) {
  const { toast } = useToast();
  const accountIds = new Set(accounts.map((acc) => String(acc.id || "")));
  const normalizedInitialParentId = accountIds.has(String(account.parentId || ""))
    ? String(account.parentId || "")
    : ROOT_OPTION;
  const [open, setOpen] = useState(false);
  const [isPending, startTransition] = useTransition();
  const [parentPopoverOpen, setParentPopoverOpen] = useState(false);
  const [parentSearchQuery, setParentSearchQuery] = useState("");
  const [form, setForm] = useState({
    code: String(account.code || ""),
    nameAr: String(account.nameAr || ""),
    nameEn: String(account.nameEn || ""),
    type: (account.type || "account") as "account" | "header",
    nature: ((account.nature || "debit") as "debit" | "credit"),
    parentId: normalizedInitialParentId,
  });

  const resetForm = () => {
    setForm({
      code: String(account.code || ""),
      nameAr: String(account.nameAr || ""),
      nameEn: String(account.nameEn || ""),
      type: (account.type || "account") as "account" | "header",
      nature: ((account.nature || "debit") as "debit" | "credit"),
      parentId: normalizedInitialParentId,
    });
  };

  const parentOptions = [{ id: ROOT_OPTION, label: "(جذر)" }, ...accounts
    .filter((acc) => String(acc.id || "") !== String(account.id || ""))
    .map((acc) => ({ id: acc.id, label: `${acc.code} — ${acc.nameAr}` }))];
  const filteredParentOptions = parentOptions.filter((opt) =>
    opt.label.toLowerCase().includes(parentSearchQuery.trim().toLowerCase())
  );

  const composeCodeUnderParent = (rawCode: string, parentId: string) => {
    const normalizedCode = String(rawCode || "").trim();
    if (!normalizedCode) return normalizedCode;
    if (!parentId || parentId === ROOT_OPTION) return normalizedCode;

    const parent = accounts.find((acc) => String(acc.id || "") === String(parentId || ""));
    const parentCode = String(parent?.code || "").trim();
    if (!parentCode) return normalizedCode;
    if (normalizedCode === parentCode || normalizedCode.startsWith(`${parentCode}-`)) return normalizedCode;

    return `${parentCode}-${normalizedCode}`;
  };

  const submit = () => {
    if (!form.code.trim() || !form.nameAr.trim() || !form.nameEn.trim()) {
      toast({ title: "تنبيه", description: "الرمز والاسمين مطلوبان.", variant: "destructive" });
      return;
    }

    startTransition(async () => {
      const finalCode = composeCodeUnderParent(form.code, form.parentId);
      if (finalCode !== form.code) {
        setForm((prev) => ({ ...prev, code: finalCode }));
      }

      const result = await handleUpdateChartAccount({
        id: account.id,
        code: finalCode,
        nameAr: form.nameAr.trim(),
        nameEn: form.nameEn.trim(),
        parentId: form.parentId === ROOT_OPTION ? null : form.parentId,
        type: form.type,
        nature: form.type === "account" ? form.nature : undefined,
      });

      if (result?.success) {
        toast({ title: "تم التعديل", description: "تم تحديث الحساب بنجاح." });
        setOpen(false);
        return;
      }

      const map: Record<string, string> = {
        DUPLICATE_CODE: "الرمز مستخدم سابقاً.",
        PARENT_NOT_FOUND: "الحساب الأب غير موجود.",
        INVALID_PARENT: "الحساب الأب غير صالح.",
        ACCOUNT_NOT_FOUND: "الحساب غير موجود.",
        INVALID_DATA: "بيانات غير صالحة.",
        Unauthorized: "التعديل متاح للمدير العام فقط.",
      };
      toast({ title: "خطأ", description: map[result?.error || ""] || "تعذر تحديث الحساب.", variant: "destructive" });
    });
  };

  return (
    <Dialog
      open={open}
      onOpenChange={(state) => {
        setOpen(state);
        if (!state) resetForm();
      }}
    >
      <Button variant="outline" size="sm" onClick={() => setOpen(true)}>
        تعديل
      </Button>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>تعديل الحساب</DialogTitle>
          <DialogDescription>عدّل بيانات الحساب ثم احفظ.</DialogDescription>
        </DialogHeader>

        <div className="grid gap-3">
          <div className="grid gap-2">
            <Label>رمز الحساب</Label>
            <Input value={form.code} onChange={(e) => setForm((prev) => ({ ...prev, code: e.target.value }))} />
          </div>
          <div className="grid gap-2">
            <Label>الاسم بالعربية</Label>
            <Input value={form.nameAr} onChange={(e) => setForm((prev) => ({ ...prev, nameAr: e.target.value }))} />
          </div>
          <div className="grid gap-2">
            <Label>الاسم بالإنجليزية</Label>
            <Input value={form.nameEn} onChange={(e) => setForm((prev) => ({ ...prev, nameEn: e.target.value }))} />
          </div>
          <div className="grid gap-2">
            <Label>نوع الحساب</Label>
            <Select value={form.type} onValueChange={(val) => setForm((prev) => ({ ...prev, type: val as "account" | "header" }))}>
              <SelectTrigger>
                <SelectValue placeholder="اختر النوع" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="account">حساب</SelectItem>
                <SelectItem value="header">عنوان رئيسي</SelectItem>
              </SelectContent>
            </Select>
          </div>
          {form.type === "account" && (
            <div className="grid gap-2">
              <Label>الطبيعة</Label>
              <Select value={form.nature} onValueChange={(val) => setForm((prev) => ({ ...prev, nature: val as "debit" | "credit" }))}>
                <SelectTrigger>
                  <SelectValue placeholder="الطبيعة" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="debit">مدين</SelectItem>
                  <SelectItem value="credit">دائن</SelectItem>
                </SelectContent>
              </Select>
            </div>
          )}
          <div className="grid gap-2">
            <Label>الحساب الأب</Label>
            <Popover open={parentPopoverOpen} onOpenChange={setParentPopoverOpen}>
              <PopoverTrigger asChild>
                <Button
                  type="button"
                  variant="outline"
                  role="combobox"
                  aria-expanded={parentPopoverOpen}
                  className={cn("w-full justify-between", !form.parentId && "text-muted-foreground")}
                >
                  {parentOptions.find((opt) => opt.id === form.parentId)?.label || "اختر الحساب الأب"}
                  <ChevronsUpDown className="ms-2 h-4 w-4 shrink-0 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-[--radix-popover-trigger-width] p-0">
                <div className="p-2 border-b">
                  <Input
                    placeholder="ابحث عن الحساب الأب..."
                    value={parentSearchQuery}
                    onChange={(e) => setParentSearchQuery(e.target.value)}
                    autoFocus
                  />
                </div>
                <div className="max-h-60 overflow-y-auto">
                  {filteredParentOptions.length === 0 ? (
                    <div className="px-3 py-4 text-center text-sm text-muted-foreground">لا توجد نتائج</div>
                  ) : (
                    filteredParentOptions.map((opt) => (
                      <button
                        key={opt.id || "root"}
                        type="button"
                        onClick={() => {
                          setForm((prev) => ({ ...prev, parentId: opt.id }));
                          setParentPopoverOpen(false);
                          setParentSearchQuery("");
                        }}
                        className={cn(
                          "w-full flex items-center gap-2 text-start px-2 py-1.5 text-sm hover:bg-accent",
                          opt.id === form.parentId && "bg-accent"
                        )}
                      >
                        <Check className={cn("h-4 w-4", opt.id === form.parentId ? "opacity-100" : "opacity-0")} />
                        <span className="flex-1">{opt.label}</span>
                      </button>
                    ))
                  )}
                </div>
              </PopoverContent>
            </Popover>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => { resetForm(); setOpen(false); }} disabled={isPending}>
            إلغاء
          </Button>
          <Button onClick={submit} disabled={isPending}>
            {isPending ? "جارٍ الحفظ..." : "حفظ التعديل"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
