"use client";
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Plus, Search } from "lucide-react";
import { customersApi } from "@/lib/api";
import { Customer, CUSTOMER_STATUS_LABELS } from "@/types";
import { PageHeader, Modal, StatusBadge, EmptyState, Spinner, ConfirmDialog } from "@/components/ui";
import { useForm } from "react-hook-form";
import toast from "react-hot-toast";

const STATUSES = Object.entries(CUSTOMER_STATUS_LABELS);

function CustomerForm({ customer, onClose }: { customer?: Customer; onClose: () => void }) {
  const qc = useQueryClient();
  const { register, handleSubmit } = useForm({ defaultValues: customer || { status: "potansiyel" } });
  const mutation = useMutation({
    mutationFn: (data: Record<string, unknown>) => customer ? customersApi.update(customer.id, data) : customersApi.create(data),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["customers"] }); toast.success(customer ? "Müşteri güncellendi." : "Müşteri eklendi."); onClose(); },
  });
  return (
    <form onSubmit={handleSubmit((d) => mutation.mutate(d))} className="space-y-4">
      <div><label className="form-label">Firma Adı *</label><input {...register("company_name", { required: true })} className="kaplan-input" /></div>
      <div className="grid grid-cols-2 gap-3"><div><label className="form-label">Yetkili Kişi</label><input {...register("contact_person")} className="kaplan-input" /></div><div><label className="form-label">Telefon</label><input {...register("phone")} className="kaplan-input" /></div></div>
      <div className="grid grid-cols-2 gap-3"><div><label className="form-label">E-posta</label><input {...register("email")} type="email" className="kaplan-input" /></div><div><label className="form-label">Web Sitesi</label><input {...register("website")} className="kaplan-input" /></div></div>
      <div><label className="form-label">Durum</label><select {...register("status")} className="kaplan-select">{STATUSES.map(([k, v]) => <option key={k} value={k}>{v}</option>)}</select></div>
      <div><label className="form-label">Notlar</label><textarea {...register("notes")} rows={3} className="kaplan-textarea" /></div>
      <div className="flex gap-3 justify-end"><button type="button" onClick={onClose} className="btn-secondary">İptal</button><button type="submit" disabled={mutation.isPending} className="btn-primary">{mutation.isPending && <Spinner size={14} />}{customer ? "Güncelle" : "Ekle"}</button></div>
    </form>
  );
}

export default function CRMPage() {
  const qc = useQueryClient();
  const [modal, setModal] = useState<{ open: boolean; customer?: Customer }>({ open: false });
  const [deleteModal, setDeleteModal] = useState<{ open: boolean; customerId?: number }>({ open: false });
  const [search, setSearch] = useState("");
  const [filterStatus, setFilterStatus] = useState("");
  const { data: customers = [], isLoading } = useQuery<Customer[]>({ queryKey: ["customers", filterStatus], queryFn: () => customersApi.list(filterStatus ? { status: filterStatus } : {}) });
  const deleteMutation = useMutation({ mutationFn: (id: number) => customersApi.delete(id), onSuccess: () => { qc.invalidateQueries({ queryKey: ["customers"] }); toast.success("Müşteri silindi."); setDeleteModal({ open: false }); } });

  const filtered = customers.filter((c) => search === "" || c.company_name.toLowerCase().includes(search.toLowerCase()) || (c.contact_person || "").toLowerCase().includes(search.toLowerCase()));

  return (
    <div className="space-y-5 animate-fade-in">
      <PageHeader title="CRM — Müşteri Yönetimi" subtitle={`${customers.length} müşteri`} action={<button onClick={() => setModal({ open: true })} className="btn-primary"><Plus size={16} /> Yeni Müşteri</button>} />
      <div className="flex items-center gap-3 flex-wrap">
        <div className="relative flex-1 min-w-48"><Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-surface-500" /><input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Müşteri ara..." className="kaplan-input pl-8 h-8 text-xs w-full" /></div>
        <select value={filterStatus} onChange={(e) => setFilterStatus(e.target.value)} className="kaplan-select h-8 text-xs w-44"><option value="">Tüm Durumlar</option>{STATUSES.map(([k, v]) => <option key={k} value={k}>{v}</option>)}</select>
      </div>
      <div className="kaplan-card overflow-hidden p-0">
        {isLoading ? <div className="flex justify-center py-12"><Spinner /></div> : filtered.length === 0 ? <EmptyState icon="👥" title="Müşteri bulunamadı" description="CRM sistemine ilk müşterinizi ekleyin." action={<button onClick={() => setModal({ open: true })} className="btn-primary"><Plus size={14} /> Müşteri Ekle</button>} /> : (
          <table className="kaplan-table">
            <thead><tr><th>Firma</th><th>Yetkili</th><th>İletişim</th><th>Durum</th><th></th></tr></thead>
            <tbody>
              {filtered.map((c) => (
                <tr key={c.id}>
                  <td><div className="font-medium">{c.company_name}</div>{c.website && <a href={c.website} target="_blank" rel="noopener noreferrer" className="text-xs text-brand-400 hover:underline">{c.website}</a>}</td>
                  <td className="text-surface-400">{c.contact_person || "—"}</td>
                  <td><div className="text-xs text-surface-400 space-y-0.5">{c.phone && <div>📞 {c.phone}</div>}{c.email && <div>✉️ {c.email}</div>}</div></td>
                  <td><StatusBadge status={c.status} /></td>
                  <td><div className="flex gap-1"><button onClick={() => setModal({ open: true, customer: c })} className="btn-ghost text-xs px-2 py-1">Düzenle</button><button onClick={() => setDeleteModal({ open: true, customerId: c.id })} className="btn-ghost text-xs px-2 py-1 text-red-400">Sil</button></div></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
      <Modal open={modal.open} onClose={() => setModal({ open: false })} title={modal.customer ? "Müşteriyi Düzenle" : "Yeni Müşteri"}><CustomerForm customer={modal.customer} onClose={() => setModal({ open: false })} /></Modal>
      <ConfirmDialog open={deleteModal.open} onClose={() => setDeleteModal({ open: false })} onConfirm={() => deleteModal.customerId && deleteMutation.mutate(deleteModal.customerId)} title="Müşteriyi Sil" loading={deleteMutation.isPending} />
    </div>
  );
}
