"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { SidebarTrigger } from "@/components/ui/sidebar";
import { DataTable } from "@/components/ui/data-table";
import { PageHeader } from "@/components/page-header";
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 { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { toast } from "sonner";
import { PlusIcon, UserIcon, EditIcon, TrashIcon, SendIcon, BellRingIcon } from "lucide-react";
import { ResponsiveActions } from "@/components/ui/responsive-actions";
import { createCustomer, updateCustomer, deleteCustomer, dispatchPushNotification, getPushHistory } from "@/app/actions/customers";
import { addCustomerAddress, deleteCustomerAddress } from "@/app/actions/customer";
import { format } from "date-fns-jalali";
import { ColumnDef } from "@tanstack/react-table";
import { useRouter } from "next/navigation";
import { JalaliDatePicker } from "@/components/ui/jalali-date-picker";

export default function CustomersClient({ customers: initialCustomers }: { customers: any[] }) {
  const router = useRouter();
  const [customers, setCustomers] = useState(initialCustomers);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingCustomer, setEditingCustomer] = useState<any>(null);
  const [deleteId, setDeleteId] = useState<string | null>(null);

  const [addingAddress, setAddingAddress] = useState(false);
  const [newAddrTitle, setNewAddrTitle] = useState("");
  const [newAddrText, setNewAddrText] = useState("");

  const [isPushModalOpen, setIsPushModalOpen] = useState(false);
  const [pushTarget, setPushTarget] = useState<any>(null); // null means 'ALL_CUSTOMERS', else customer object
  const [pushData, setPushData] = useState({ title: "", body: "", url: "/" });
  const [isSendingPush, setIsSendingPush] = useState(false);
  
  const [isHistoryModalOpen, setIsHistoryModalOpen] = useState(false);
  const [pushHistory, setPushHistory] = useState<any[]>([]);
  const [isLoadingHistory, setIsLoadingHistory] = useState(false);

  useEffect(() => {
    setCustomers(initialCustomers);
  }, [initialCustomers]);

  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    phone: "",
    address: "",
    nationalCode: "",
    birthDate: null as Date | null,
  });

  const columns: ColumnDef<any>[] = [
    {
      accessorKey: "subscriptionCode",
      header: "کد اشتراک",
      cell: ({ row }) => <span className="font-black tracking-widest bg-amber-100 text-amber-800 px-2 py-0.5 rounded-md dark:bg-amber-900/30 dark:text-amber-400">{row.original.subscriptionCode || "-"}</span>
    },
    {
      accessorKey: "fullName",
      header: "نام و نام خانوادگی",
      cell: ({ row }) => <span className="font-bold">{row.original.firstName} {row.original.lastName}</span>
    },
    { accessorKey: "phone", header: "تلفن", cell: ({ row }) => <span className="font-sans font-medium tracking-tight text-left" dir="ltr">{row.original.phone}</span> },
    { accessorKey: "address", header: "آدرس", cell: ({ row }) => <span className="truncate max-w-[200px] inline-block">{row.original.address || "-"}</span> },
    {
      id: "stats",
      header: "سفارشات",
      cell: ({ row }) => (
        <div className="flex flex-col text-xs text-muted-foreground tracking-tight">
          <span>{row.original._count?.orders || 0} سفارش</span>
          <span>{row.original._count?.transactions || 0} تراکنش</span>
        </div>
      )
    },
    {
      id: "debtBalance",
      header: "وضعیت مالی",
      cell: ({ row }) => {
        const debt = row.original.debtBalance || 0;
        if (debt <= 0) {
          return <span className="text-[11px] bg-emerald-100 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-400 px-2 py-0.5 rounded-full font-bold">تسویه شده</span>;
        }
        return (
          <div className="flex flex-col">
            <span className="text-[11px] bg-rose-100 text-rose-800 dark:bg-rose-900/30 dark:text-rose-400 px-2 py-0.5 rounded-full font-bold inline-block w-fit">بدهکار</span>
            <span className="font-sans font-black text-xs text-rose-600 mt-0.5">{debt.toLocaleString("fa-IR")} تومان</span>
          </div>
        );
      }
    },
    {
      accessorKey: "createdAt",
      header: "تاریخ ثبت",
      cell: ({ row }) => <span className="font-sans text-xs tracking-tight text-muted-foreground">{format(new Date(row.getValue("createdAt")), "yyyy/MM/dd")}</span>
    },
    {
      id: "actions",
      header: "عملیات",
      cell: ({ row }) => (
        <div className="flex gap-2 items-center justify-end">
          <Button variant="ghost" size="icon" onClick={() => openModal(row.original)} className="text-muted-foreground hover:text-primary">
            <EditIcon className="w-4 h-4" />
          </Button>
          <Button variant="ghost" size="icon" onClick={() => setDeleteId(row.original.id)} className="text-muted-foreground hover:text-destructive">
            <TrashIcon className="w-4 h-4" />
          </Button>
          <Button variant="ghost" size="icon" onClick={() => openPushModal(row.original)} className="text-muted-foreground hover:text-indigo-600" title="ارسال پیامک پوش">
            <BellRingIcon className="w-4 h-4" />
          </Button>
          <Link href={`/admin/customers/${row.original.id}`}>
            <Button variant="outline" size="sm" className="h-8">
              مشاهده پروفایل
            </Button>
          </Link>
        </div>
      )
    }
  ];

  const openModal = (customer?: any) => {
    if (customer) {
      setEditingCustomer(customer);
      setFormData({
        firstName: customer.firstName,
        lastName: customer.lastName,
        phone: customer.phone || "",
        address: customer.address || "",
        nationalCode: customer.nationalCode || "",
        birthDate: customer.birthDate ? new Date(customer.birthDate) : null,
      });
    } else {
      setEditingCustomer(null);
      setFormData({ firstName: "", lastName: "", phone: "", address: "", nationalCode: "", birthDate: null });
    }
    setIsModalOpen(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.firstName || !formData.lastName || !formData.phone) {
      toast.error("وارد کردن نام، نام خانوادگی و تلفن الزامی است.");
      return;
    }

    const payload = { ...formData };

    if (editingCustomer) {
      const { success, error } = await updateCustomer(editingCustomer.id, payload);
      if (success) {
        toast.success("اطلاعات مشتری با موفقیت ویرایش شد.");
        setIsModalOpen(false);
      } else toast.error(error);
    } else {
      const { success, error } = await createCustomer(payload);
      if (success) {
        toast.success("مشتری جدید با موفقیت ثبت شد.");
        setIsModalOpen(false);
      } else toast.error(error);
    }
  };

  const handleDeleteConfirm = async (id: string) => {
    const res = await deleteCustomer(id);
    if (res.success) {
      toast.success("مشتری با موفقیت حذف شد.");
      setDeleteId(null);
    } else {
      toast.error(res.error || "خطا در حذف مشتری");
    }
  };

  const handleAddAddress = async () => {
    if (!editingCustomer || !newAddrText) return;
    setAddingAddress(true);
    const res = await addCustomerAddress(editingCustomer.id, newAddrText, newAddrTitle);
    setAddingAddress(false);
    if (res.success) {
      toast.success("آدرس اضافه شد");
      setNewAddrTitle("");
      setNewAddrText("");
      setEditingCustomer({
        ...editingCustomer,
        addresses: [...(editingCustomer.addresses || []), res.address]
      });
      router.refresh();
    } else {
      toast.error(res.error || "خطا در افزودن آدرس");
    }
  };

  const handleDeleteAddress = async (addrId: string) => {
    setAddingAddress(true);
    const res = await deleteCustomerAddress(addrId, editingCustomer.id);
    setAddingAddress(false);
    if (res.success) {
      toast.success("آدرس حذف شد");
      setEditingCustomer({
        ...editingCustomer,
        addresses: editingCustomer.addresses.filter((a: any) => a.id !== addrId)
      });
      router.refresh();
    } else {
      toast.error(res.error || "خطا در حذف آدرس");
    }
  };

  const openPushModal = (customer: any) => {
    setPushTarget(customer);
    setPushData({ title: "", body: "", url: "/" });
    setIsPushModalOpen(true);
  };

  const handleSendPush = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSendingPush(true);
    let targetPayload: any = "ALL_CUSTOMERS";
    if (pushTarget) {
      targetPayload = { customerId: pushTarget.id };
    }
    
    const res = await dispatchPushNotification(targetPayload, pushData);
    setIsSendingPush(false);
    
    if (res.success) {
      toast.success(`نوتیفیکیشن با موفقیت به ${res.successCount} دستگاه آنلاین ارسال شد!`);
      setIsPushModalOpen(false);
    } else {
      toast.error(res.error || "خطا در برقراری ارتباط با سرویس پوش ابری");
    }
  };

  const openHistoryModal = async () => {
    setIsHistoryModalOpen(true);
    setIsLoadingHistory(true);
    const res = await getPushHistory();
    if (res.success) {
      setPushHistory(res.history || []);
    } else {
      toast.error("خطا در دریافت سوابق: " + res.error);
    }
    setIsLoadingHistory(false);
  };

  return (
    <div className="flex flex-col h-full overflow-hidden" dir="rtl">
      <PageHeader
        title="مشتریان"
        subtitle={`${customers.length} مشتری ثبت شده`}
        icon={<UserIcon className="w-5 h-5" />}
        actions={[
          { label: "سوابق ارسال", onClick: openHistoryModal, variant: "outline" },
          { label: "نوتیفیکیشن همگانی", icon: <SendIcon className="w-4 h-4" />, onClick: () => openPushModal(null), variant: "outline" },
          { label: "مشتری جدید", icon: <PlusIcon className="w-4 h-4" />, onClick: () => openModal(), variant: "default", className: "bg-indigo-600 hover:bg-indigo-700 text-white" },
        ]}
      />

      <div className="flex-1 p-4 lg:p-8 max-w-7xl mx-auto w-full overflow-auto space-y-6 pr-4 lg:pr-8">
        <div className="bg-card border rounded-2xl p-6 shadow-sm">
          <DataTable columns={columns} data={customers} searchKey="phone" searchPlaceholder="جستجو در موبایل..." />
        </div>
      </div>

      <AlertDialog open={!!deleteId} onOpenChange={(open) => !open && setDeleteId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>آیا از حذف این مشتری مطمئن هستید؟</AlertDialogTitle>
            <AlertDialogDescription>در صورتی که این مشتری سفارش یا تراکنش وابسته داشته باشد، حذف آن امکان‌پذیر نخواهد بود.</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>انصراف</AlertDialogCancel>
            <AlertDialogAction className="bg-destructive text-destructive-foreground" onClick={() => deleteId && handleDeleteConfirm(deleteId)}>حذف مشتری</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{editingCustomer ? "ویرایش اطلاعات مشتری" : "ثبت مشتری جدید و تشکیل پرونده"}</DialogTitle>
          </DialogHeader>
          <form onSubmit={handleSubmit} className="space-y-4 py-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>نام *</Label>
                <Input value={formData.firstName} onChange={e => setFormData({ ...formData, firstName: e.target.value })} placeholder="مثال: علی" required />
              </div>
              <div className="space-y-2">
                <Label>نام خانوادگی *</Label>
                <Input value={formData.lastName} onChange={e => setFormData({ ...formData, lastName: e.target.value })} placeholder="مثال: محمدی" required />
              </div>
            </div>
            <div className="space-y-2">
              <Label>شماره موبایل *</Label>
              <Input className="font-sans text-right" dir="ltr" value={formData.phone} onChange={e => setFormData({ ...formData, phone: e.target.value })} placeholder="0912..." required />
            </div>
            <div className="space-y-2">
              <Label>آدرس و ملاحظات حساب</Label>
              <Textarea className="font-sans resize-none h-20" value={formData.address} onChange={e => setFormData({ ...formData, address: e.target.value })} placeholder="تهران، خیابان..." />
            </div>
            <div className="space-y-2">
              <Label>کد ملی</Label>
              <Input
                className="font-sans text-right"
                dir="ltr"
                maxLength={10}
                value={formData.nationalCode}
                onChange={e => setFormData({ ...formData, nationalCode: e.target.value.replace(/\D/g, "") })}
                placeholder="کد ملی ده رقمی..."
              />
            </div>
            <div className="space-y-2">
              <Label className="flex items-center gap-1.5">تاریخ تولد <span className="text-[10px] text-emerald-600 bg-emerald-100 dark:bg-emerald-900/30 dark:text-emerald-400 px-1.5 py-0.5 rounded-md font-bold">تبریک خودکار</span></Label>
              <JalaliDatePicker
                value={formData.birthDate}
                onChange={(d) => setFormData({ ...formData, birthDate: d })}
                placeholder="انتخاب تاریخ تولد"
              />
            </div>

            {editingCustomer && (
              <div className="pt-4 border-t space-y-3 mt-4">
                <Label className="font-bold text-primary text-xs">آدرس‌های ثبت‌شده (آدرس‌های فرعی)</Label>
                <div className="space-y-2 max-h-[140px] overflow-y-auto no-scrollbar">
                  {editingCustomer.addresses?.map((addr: any) => (
                    <div key={addr.id} className="flex justify-between items-center bg-muted/30 p-2 rounded-lg border text-sm">
                      <div>
                        <span className="font-bold block text-[10px] text-primary mb-0.5">{addr.title}</span>
                        <span className="text-xs text-muted-foreground">{addr.address}</span>
                      </div>
                      <Button type="button" variant="ghost" size="icon" onClick={() => handleDeleteAddress(addr.id)} disabled={addingAddress} className="text-rose-500 hover:text-rose-600 hover:bg-rose-500/10 h-7 w-7"><TrashIcon className="w-3.5 h-3.5" /></Button>
                    </div>
                  ))}
                  {(!editingCustomer.addresses || editingCustomer.addresses.length === 0) && <div className="text-xs text-muted-foreground opacity-60">هیچ آدرسی ثبت نشده است</div>}
                </div>
                <div className="flex gap-2">
                  <Input placeholder="عنوان (اختیاری)" value={newAddrTitle} onChange={e => setNewAddrTitle(e.target.value)} className="text-xs h-9 w-1/3 text-right font-sans" />
                  <Input placeholder="آدرس دقیق و پلاک سفارشی..." value={newAddrText} onChange={e => setNewAddrText(e.target.value)} className="text-xs h-9 flex-1" />
                </div>
                <Button type="button" variant="secondary" className="w-full text-xs h-9 bg-primary/5 hover:bg-primary/10 text-primary border border-primary/20" onClick={handleAddAddress} disabled={addingAddress || !newAddrText}>
                  <PlusIcon className="w-3 h-3 ml-1" /> ثبت آدرس جدید به عنوان مقصد
                </Button>
              </div>
            )}

            <Button type="submit" className="w-full mt-4 flex items-center gap-2">
              ثبت اطلاعات مشتری
            </Button>
          </form>
        </DialogContent>
      </Dialog>

      <Dialog open={isPushModalOpen} onOpenChange={setIsPushModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-indigo-700">
              <BellRingIcon className="w-5 h-5" />
              {pushTarget ? `ارسال نوتیفیکیشن به ${pushTarget.firstName}` : "ارسال نوتیفیکیشن همگانی به مشتریان"}
            </DialogTitle>
          </DialogHeader>
          <form onSubmit={handleSendPush} className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>عنوان نوتیفیکیشن (Title) *</Label>
              <Input required value={pushData.title} onChange={e => setPushData({ ...pushData, title: e.target.value })} placeholder="مثال: تخفیف ویژه آخر هفته!" />
            </div>
            <div className="space-y-2">
              <Label>متن اصلی (Body) *</Label>
              <Textarea required value={pushData.body} onChange={e => setPushData({ ...pushData, body: e.target.value })} placeholder="مثال: با وارد کردن کد OFF20 از 20% تخفیف بهره مند شوید." className="h-20" />
            </div>
            <div className="space-y-2">
              <Label>لینک هدایت (URL مسیر وقتی کاربر کلیک میکند)</Label>
              <Input dir="ltr" className="text-left font-mono" value={pushData.url} onChange={e => setPushData({ ...pushData, url: e.target.value })} placeholder="مثلاً: /shop یا /profile" />
            </div>
            <Button disabled={isSendingPush} type="submit" className="w-full h-11 mt-2 bg-indigo-600 hover:bg-indigo-700">
              {isSendingPush ? "در حال ارسال به سرور ابری..." : "ارسال نهایی"}
            </Button>
          </form>
        </DialogContent>
      </Dialog>

      <Dialog open={isHistoryModalOpen} onOpenChange={setIsHistoryModalOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              سوابق نوتیفیکیشن‌های ارسالی
            </DialogTitle>
          </DialogHeader>
          <div className="max-h-[60vh] overflow-y-auto pr-2 space-y-4">
            {isLoadingHistory ? (
              <div className="text-center text-muted-foreground py-8">در حال دریافت...</div>
            ) : pushHistory.length === 0 ? (
              <div className="text-center text-muted-foreground py-8">هیچ سابقه ای یافت نشد.</div>
            ) : (
              pushHistory.map(h => (
                <div key={h.id} className="border rounded-xl p-4 bg-muted/20 text-sm space-y-3 relative">
                  <div className="flex justify-between items-center text-xs text-muted-foreground border-b pb-2">
                    <span className="font-bold text-primary">{h.staff?.fullName || h.staff?.username}</span>
                    <span>{format(new Date(h.createdAt), "yyyy/MM/dd HH:mm")}</span>
                  </div>
                  <div>
                    <h4 className="font-bold mb-1 text-emerald-700">{h.title}</h4>
                    <p className="opacity-80 text-xs leading-relaxed">{h.body}</p>
                    {h.url && <a href={h.url} className="text-xs text-indigo-500 mt-2 block" target="_blank" rel="noreferrer">{h.url}</a>}
                  </div>
                  <div className="flex gap-4 text-xs font-semibold pt-2 border-t text-zinc-500">
                     <span>هدف: {h.target === "ALL_CUSTOMERS" ? "همه مشتریان" : h.target}</span>
                     <span>دریافت موفق: {h.successCount} دستگاه</span>
                  </div>
                </div>
              ))
            )}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
