"use client";

import { useState, useCallback } from "react";
import {
  Search,
  Plus,
  Filter,
  Loader2,
  MoreHorizontal,
  Mail,
  Phone,
  Building2,
} from "lucide-react";
import type { LeadOutput } from "@/lib/types/lead-crm.types";
import LeadScoreBadge from "./LeadScoreBadge";

interface LeadListViewProps {
  isAr: boolean;
  leads: LeadOutput[];
  loading: boolean;
  onRefresh: (filters?: Record<string, string>) => void;
  onSelectLead: (lead: LeadOutput) => void;
  onCreateLead: () => void;
}

export default function LeadListView({
  isAr,
  leads,
  loading,
  onRefresh,
  onSelectLead,
  onCreateLead,
}: LeadListViewProps) {
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("");

  const handleSearch = useCallback(
    (query: string) => {
      setSearch(query);
      onRefresh({ search: query, status: statusFilter });
    },
    [statusFilter, onRefresh],
  );

  const handleStatusFilter = useCallback(
    (status: string) => {
      setStatusFilter(status);
      onRefresh({ search, status });
    },
    [search, onRefresh],
  );

  const statusOptions = [
    { value: "", labelEn: "All", labelAr: "الكل" },
    { value: "new", labelEn: "New", labelAr: "جديد" },
    { value: "contacted", labelEn: "Contacted", labelAr: "تم التواصل" },
    { value: "qualified", labelEn: "Qualified", labelAr: "مؤهل" },
    { value: "converted", labelEn: "Converted", labelAr: "محوّل" },
    { value: "lost", labelEn: "Lost", labelAr: "خاسر" },
  ];

  return (
    <div className="space-y-4">
      {/* Toolbar */}
      <div className="flex items-center gap-3 flex-wrap">
        <div className="relative flex-1 min-w-[200px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
          <input
            type="text"
            value={search}
            onChange={(e) => handleSearch(e.target.value)}
            placeholder={isAr ? "بحث عن عميل محتمل..." : "Search leads..."}
            className="w-full pl-10 pr-4 py-2.5 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-200"
            dir={isAr ? "rtl" : "ltr"}
          />
        </div>
        <div className="flex items-center gap-2">
          <Filter className="h-4 w-4 text-slate-400" />
          <select
            value={statusFilter}
            onChange={(e) => handleStatusFilter(e.target.value)}
            className="px-3 py-2.5 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-200"
          >
            {statusOptions.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {isAr ? opt.labelAr : opt.labelEn}
              </option>
            ))}
          </select>
        </div>
        <button
          onClick={onCreateLead}
          className="flex items-center gap-1.5 px-4 py-2.5 bg-indigo-600 text-white rounded-xl text-sm font-medium hover:bg-indigo-700 transition-colors"
        >
          <Plus className="h-4 w-4" />
          {isAr ? "إضافة عميل" : "Add Lead"}
        </button>
      </div>

      {/* Table */}
      <div className="bg-white rounded-2xl border border-slate-200 overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center h-64">
            <Loader2 className="h-8 w-8 animate-spin text-indigo-500" />
          </div>
        ) : leads.length === 0 ? (
          <div className="text-center py-16 text-slate-400">
            <p className="text-sm">
              {isAr ? "لا يوجد عملاء محتملون" : "No leads found"}
            </p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-slate-100 bg-slate-50/50">
                  <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 uppercase">
                    {isAr ? "الاسم" : "Name"}
                  </th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 uppercase">
                    {isAr ? "التواصل" : "Contact"}
                  </th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 uppercase">
                    {isAr ? "المصدر" : "Source"}
                  </th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 uppercase">
                    {isAr ? "النقاط" : "Score"}
                  </th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 uppercase">
                    {isAr ? "الحالة" : "Status"}
                  </th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 uppercase">
                    {isAr ? "القيمة" : "Deal Value"}
                  </th>
                  <th className="px-4 py-3"></th>
                </tr>
              </thead>
              <tbody>
                {leads.map((lead) => (
                  <tr
                    key={lead.id}
                    onClick={() => onSelectLead(lead)}
                    className="border-b border-slate-50 hover:bg-slate-50/50 cursor-pointer transition-colors"
                  >
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-3">
                        <div className="w-9 h-9 rounded-full bg-indigo-100 flex items-center justify-center">
                          <span className="text-sm font-medium text-indigo-700">
                            {lead.name[0]?.toUpperCase()}
                          </span>
                        </div>
                        <div>
                          <p className="text-sm font-medium text-slate-900">
                            {lead.name}
                          </p>
                          {lead.company && (
                            <p className="text-xs text-slate-500 flex items-center gap-1">
                              <Building2 className="h-3 w-3" />
                              {lead.company}
                            </p>
                          )}
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <div className="space-y-0.5">
                        {lead.email && (
                          <p className="text-xs text-slate-600 flex items-center gap-1">
                            <Mail className="h-3 w-3" />
                            {lead.email}
                          </p>
                        )}
                        {lead.phone && (
                          <p className="text-xs text-slate-600 flex items-center gap-1">
                            <Phone className="h-3 w-3" />
                            {lead.phone}
                          </p>
                        )}
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <span className="text-xs px-2 py-1 bg-slate-100 text-slate-700 rounded-full">
                        {lead.source}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <LeadScoreBadge score={lead.score} size="sm" />
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className={`text-xs px-2 py-1 rounded-full font-medium ${
                          lead.status === "new"
                            ? "bg-blue-100 text-blue-700"
                            : lead.status === "qualified"
                              ? "bg-purple-100 text-purple-700"
                              : lead.status === "converted"
                                ? "bg-emerald-100 text-emerald-700"
                                : lead.status === "lost"
                                  ? "bg-red-100 text-red-700"
                                  : "bg-slate-100 text-slate-700"
                        }`}
                      >
                        {lead.status}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      {lead.dealValue ? (
                        <span className="text-sm font-medium text-slate-900">
                          {lead.dealCurrency || "QAR"}{" "}
                          {lead.dealValue.toLocaleString()}
                        </span>
                      ) : (
                        <span className="text-xs text-slate-400">-</span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                        }}
                        className="p-1 rounded hover:bg-slate-100"
                      >
                        <MoreHorizontal className="h-4 w-4 text-slate-400" />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
