"use client";

import { useState, useEffect } from "react";

interface Lead {
  id: string;
  name: string;
  email: string;
  phone: string | null;
  company: string | null;
  serviceInterest: string | null;
  message: string | null;
  source: string;
  status: string;
  notes: string | null;
  createdAt: string;
}

const statusOptions = [
  { value: "new", label: "Baru", color: "bg-blue-100 text-blue-700" },
  { value: "contacted", label: "Dihubungi", color: "bg-yellow-100 text-yellow-700" },
  { value: "qualified", label: "Kualifikasi", color: "bg-purple-100 text-purple-700" },
  { value: "converted", label: "Konversi", color: "bg-green-100 text-green-700" },
  { value: "lost", label: "Hilang", color: "bg-gray-100 text-gray-500" },
];

export default function LeadsPage() {
  const [leads, setLeads] = useState<Lead[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState("all");
  const [selectedLead, setSelectedLead] = useState<Lead | null>(null);
  const [notes, setNotes] = useState("");

  useEffect(() => {
    fetchLeads();
  }, []);

  async function fetchLeads() {
    const res = await fetch("/api/admin/leads");
    const data = await res.json();
    setLeads(data);
    setLoading(false);
  }

  async function updateLeadStatus(id: string, status: string) {
    await fetch(`/api/admin/leads/${id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status }),
    });
    fetchLeads();
  }

  async function updateLeadNotes(id: string) {
    await fetch(`/api/admin/leads/${id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ notes }),
    });
    fetchLeads();
    setSelectedLead(null);
  }

  const filteredLeads = filter === "all" ? leads : leads.filter((l) => l.status === filter);

  return (
    <div>
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-gray-800">Leads</h1>
        <p className="text-gray-500">Kelola leads yang masuk</p>
      </div>

      {/* Filter */}
      <div className="flex gap-2 mb-6">
        <button
          onClick={() => setFilter("all")}
          className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
            filter === "all"
              ? "bg-brand-blue text-white"
              : "bg-gray-100 text-gray-600 hover:bg-gray-200"
          }`}
        >
          Semua ({leads.length})
        </button>
        {statusOptions.map((opt) => (
          <button
            key={opt.value}
            onClick={() => setFilter(opt.value)}
            className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
              filter === opt.value
                ? "bg-brand-blue text-white"
                : "bg-gray-100 text-gray-600 hover:bg-gray-200"
            }`}
          >
            {opt.label} ({leads.filter((l) => l.status === opt.value).length})
          </button>
        ))}
      </div>

      {/* Table */}
      <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                Nama
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                Email
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                Layanan
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                Sumber
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                Status
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                Tanggal
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                Aksi
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {filteredLeads.length === 0 ? (
              <tr>
                <td colSpan={7} className="px-6 py-8 text-center text-gray-500">
                  Tidak ada leads
                </td>
              </tr>
            ) : (
              filteredLeads.map((lead) => (
                <tr key={lead.id} className="hover:bg-gray-50">
                  <td className="px-6 py-4 text-sm font-medium text-gray-800">
                    {lead.name}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-500">
                    {lead.email}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-500">
                    {lead.serviceInterest || "-"}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-500">
                    {lead.source}
                  </td>
                  <td className="px-6 py-4">
                    <select
                      value={lead.status}
                      onChange={(e) =>
                        updateLeadStatus(lead.id, e.target.value)
                      }
                      className={`px-2 py-1 text-xs font-medium rounded-full border-0 ${
                        statusOptions.find((o) => o.value === lead.status)
                          ?.color || ""
                      }`}
                    >
                      {statusOptions.map((opt) => (
                        <option key={opt.value} value={opt.value}>
                          {opt.label}
                        </option>
                      ))}
                    </select>
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-500">
                    {new Date(lead.createdAt).toLocaleDateString("id-ID")}
                  </td>
                  <td className="px-6 py-4">
                    <button
                      onClick={() => {
                        setSelectedLead(lead);
                        setNotes(lead.notes || "");
                      }}
                      className="px-3 py-1 text-sm text-brand-blue hover:bg-brand-blue/10 rounded-lg transition-colors"
                    >
                      Detail
                    </button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Detail Modal */}
      {selectedLead && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl w-full max-w-lg">
            <div className="p-6 border-b border-gray-100">
              <h2 className="text-lg font-semibold">Detail Lead</h2>
            </div>
            <div className="p-6 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-xs text-gray-500">Nama</p>
                  <p className="text-sm font-medium">{selectedLead.name}</p>
                </div>
                <div>
                  <p className="text-xs text-gray-500">Email</p>
                  <p className="text-sm font-medium">{selectedLead.email}</p>
                </div>
                <div>
                  <p className="text-xs text-gray-500">Telepon</p>
                  <p className="text-sm font-medium">
                    {selectedLead.phone || "-"}
                  </p>
                </div>
                <div>
                  <p className="text-xs text-gray-500">Perusahaan</p>
                  <p className="text-sm font-medium">
                    {selectedLead.company || "-"}
                  </p>
                </div>
                <div>
                  <p className="text-xs text-gray-500">Layanan</p>
                  <p className="text-sm font-medium">
                    {selectedLead.serviceInterest || "-"}
                  </p>
                </div>
                <div>
                  <p className="text-xs text-gray-500">Sumber</p>
                  <p className="text-sm font-medium">{selectedLead.source}</p>
                </div>
              </div>
              <div>
                <p className="text-xs text-gray-500">Pesan</p>
                <p className="text-sm">{selectedLead.message || "-"}</p>
              </div>
              <div>
                <label className="text-xs text-gray-500">Catatan</label>
                <textarea
                  value={notes}
                  onChange={(e) => setNotes(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-blue focus:border-transparent outline-none mt-1"
                  rows={3}
                />
              </div>
            </div>
            <div className="p-6 border-t border-gray-100 flex gap-3">
              <button
                onClick={() => updateLeadNotes(selectedLead.id)}
                className="px-6 py-2 bg-brand-blue text-white rounded-lg hover:bg-brand-blue-dark transition-colors"
              >
                Simpan Catatan
              </button>
              <button
                onClick={() => setSelectedLead(null)}
                className="px-6 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
              >
                Tutup
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
