"use client";

import * as React from "react";
import { useRouter, usePathname, useSearchParams } from "next/navigation";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Download } from "lucide-react";
import { toast } from "sonner";

export type LeadRow = {
  id: string;
  type: string;
  name: string;
  email: string | null;
  phone: string;
  subject: string | null;
  message: string | null;
  service: string | null;
  status: string;
  createdAt: string;
};

const TYPE_OPTIONS = [
  { value: "ALL", label: "All Types" },
  { value: "CONTACT", label: "Contact" },
  { value: "QUOTE", label: "Quote Request" },
  { value: "CALLBACK", label: "Callback" },
  { value: "SERVICE", label: "Service" },
  { value: "EMERGENCY", label: "Emergency" },
];

const STATUS_OPTIONS = [
  { value: "ALL", label: "All Statuses" },
  { value: "NEW", label: "New" },
  { value: "READ", label: "Read" },
  { value: "RESPONDED", label: "Responded" },
  { value: "CLOSED", label: "Closed" },
];

function csvEscape(value: string | null | undefined): string {
  if (value === null || value === undefined) return "";
  const s = String(value);
  if (/[",\n\r]/.test(s)) {
    return `"${s.replace(/"/g, '""')}"`;
  }
  return s;
}

export function LeadsFilters({ leads }: { leads: LeadRow[] }) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const currentType = searchParams.get("type") || "ALL";
  const currentStatus = searchParams.get("status") || "ALL";

  const updateParam = (key: string, value: string) => {
    const params = new URLSearchParams(searchParams.toString());
    if (value === "ALL" || !value) {
      params.delete(key);
    } else {
      params.set(key, value);
    }
    const qs = params.toString();
    router.push(qs ? `${pathname}?${qs}` : pathname);
  };

  const exportCsv = () => {
    try {
      const headers = [
        "ID", "Type", "Status", "Name", "Email", "Phone",
        "Subject", "Service", "Message", "CreatedAt",
      ];
      const rows = leads.map((l) => [
        l.id, l.type, l.status, l.name, l.email || "", l.phone,
        l.subject || "", l.service || "", l.message || "",
        new Date(l.createdAt).toISOString(),
      ]);
      const csv = [headers, ...rows]
        .map((r) => r.map(csvEscape).join(","))
        .join("\r\n");

      const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `leads-${new Date().toISOString().slice(0, 10)}.csv`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      toast.success(`Exported ${leads.length} lead(s) to CSV`);
    } catch {
      toast.error("CSV export failed");
    }
  };

  return (
    <div className="flex flex-col sm:flex-row gap-3 sm:items-center justify-between">
      <div className="flex flex-wrap gap-2">
        <Select value={currentType} onValueChange={(v) => updateParam("type", v)}>
          <SelectTrigger className="w-[160px] h-9">
            <SelectValue placeholder="Type" />
          </SelectTrigger>
          <SelectContent>
            {TYPE_OPTIONS.map((o) => (
              <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select value={currentStatus} onValueChange={(v) => updateParam("status", v)}>
          <SelectTrigger className="w-[160px] h-9">
            <SelectValue placeholder="Status" />
          </SelectTrigger>
          <SelectContent>
            {STATUS_OPTIONS.map((o) => (
              <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <Button
        type="button"
        variant="outline"
        size="sm"
        onClick={exportCsv}
        disabled={leads.length === 0}
      >
        <Download className="size-4 mr-1.5" /> Export CSV
      </Button>
    </div>
  );
}
