"use client";

import { useState, useTransition } from "react";
import { updateLeadStatus, deleteLead } from "@/lib/admin-actions";
import { Trash2 } from "lucide-react";

export interface Lead {
  id: string;
  created_at: string;
  source: string;
  status: "new" | "contacted" | "won" | "lost";
  name: string | null;
  phone: string | null;
  email: string | null;
  city: string | null;
  product_slug: string | null;
  quantity: string | null;
  notes: string | null;
}

const sourceLabels: Record<string, string> = {
  quote_drawer: "طلب سريع",
  quote_inline: "طلب عرض سعر",
  wholesale: "الجملة والمشاريع",
  maintenance: "بلاغ صيانة",
  contact: "تواصل",
};

const statusOptions: Lead["status"][] = ["new", "contacted", "won", "lost"];
const statusLabels: Record<Lead["status"], string> = {
  new: "جديد",
  contacted: "تم التواصل",
  won: "تم الإغلاق",
  lost: "ملغي",
};

export default function LeadsTable({ leads }: { leads: Lead[] }) {
  const [items, setItems] = useState(leads);
  const [, startTransition] = useTransition();

  function handleStatusChange(id: string, status: Lead["status"]) {
    setItems((prev) => prev.map((l) => (l.id === id ? { ...l, status } : l)));
    startTransition(async () => {
      await updateLeadStatus(id, status);
    });
  }

  function handleDelete(id: string) {
    if (!confirm("حذف هذا الطلب نهائياً؟")) return;
    setItems((prev) => prev.filter((l) => l.id !== id));
    startTransition(async () => {
      await deleteLead(id);
    });
  }

  if (items.length === 0) {
    return (
      <div className="rounded-2xl border border-black/10 bg-white p-10 text-center text-sm text-[#8A8A8A]">
        لا توجد طلبات مطابقة.
      </div>
    );
  }

  return (
    <div className="overflow-x-auto rounded-2xl border border-black/10 bg-white">
      <table className="w-full text-sm">
        <thead>
          <tr className="border-b border-black/10 text-start text-xs text-[#8A8A8A]">
            <th className="px-4 py-3 text-start font-medium">التاريخ</th>
            <th className="px-4 py-3 text-start font-medium">المصدر</th>
            <th className="px-4 py-3 text-start font-medium">الاسم</th>
            <th className="px-4 py-3 text-start font-medium">التواصل</th>
            <th className="px-4 py-3 text-start font-medium">المدينة</th>
            <th className="px-4 py-3 text-start font-medium">المنتج / التفاصيل</th>
            <th className="px-4 py-3 text-start font-medium">الحالة</th>
            <th className="px-4 py-3"></th>
          </tr>
        </thead>
        <tbody>
          {items.map((lead) => (
            <tr key={lead.id} className="border-b border-black/5 last:border-0">
              <td className="whitespace-nowrap px-4 py-3 text-xs text-[#8A8A8A]">
                {new Date(lead.created_at).toLocaleString("ar-SA", { dateStyle: "medium", timeStyle: "short" })}
              </td>
              <td className="px-4 py-3 text-xs">{sourceLabels[lead.source] || lead.source}</td>
              <td className="px-4 py-3 font-medium text-[#1A1A1A]">{lead.name || "—"}</td>
              <td className="px-4 py-3 text-xs">
                <div>{lead.phone || "—"}</div>
                {lead.email && <div className="text-[#8A8A8A]">{lead.email}</div>}
              </td>
              <td className="px-4 py-3 text-xs">{lead.city || "—"}</td>
              <td className="px-4 py-3 text-xs">
                <div>{lead.product_slug || "—"}</div>
                {lead.quantity && <div className="text-[#8A8A8A]">الكمية: {lead.quantity}</div>}
                {lead.notes && <div className="mt-1 max-w-xs truncate text-[#8A8A8A]" title={lead.notes}>{lead.notes}</div>}
              </td>
              <td className="px-4 py-3">
                <select
                  value={lead.status}
                  onChange={(e) => handleStatusChange(lead.id, e.target.value as Lead["status"])}
                  className="rounded-lg border border-black/10 bg-[#F5F3EF] px-2 py-1.5 text-xs outline-none focus:border-[#C9A24A]"
                >
                  {statusOptions.map((s) => (
                    <option key={s} value={s}>
                      {statusLabels[s]}
                    </option>
                  ))}
                </select>
              </td>
              <td className="px-4 py-3">
                <button
                  onClick={() => handleDelete(lead.id)}
                  className="rounded-lg p-1.5 text-[#B0B0B0] transition hover:bg-red-50 hover:text-red-600"
                  aria-label="حذف"
                >
                  <Trash2 size={15} />
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
