import { useState, useRef } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Upload, FileSpreadsheet, CheckCircle2, AlertTriangle, X } from "lucide-react";
import { toast } from "sonner";

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? "";

interface ParsedDelegate {
  first_name: string;
  last_name: string;
  email: string;
  phone: string;
  valid: boolean;
  error?: string;
}

const BulkDelegateImport = ({ companyId }: { companyId: string }) => {
  const queryClient = useQueryClient();
  const fileRef = useRef<HTMLInputElement>(null);
  const [parsed, setParsed] = useState<ParsedDelegate[]>([]);
  const [showPreview, setShowPreview] = useState(false);

  const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (evt) => {
      const text = evt.target?.result as string;
      const lines = text.split(/\r?\n/).filter(l => l.trim());
      if (lines.length < 2) {
        toast.error("CSV must have a header row and at least one data row");
        return;
      }

      const header = lines[0].toLowerCase().split(",").map(h => h.trim());
      const fnIdx = header.findIndex(h => h.includes("first"));
      const lnIdx = header.findIndex(h => h.includes("last") || h.includes("surname"));
      const emIdx = header.findIndex(h => h.includes("email"));
      const phIdx = header.findIndex(h => h.includes("phone") || h.includes("mobile"));

      if (fnIdx === -1 || lnIdx === -1) {
        toast.error("CSV must contain 'first_name' and 'last_name' columns");
        return;
      }

      const rows: ParsedDelegate[] = lines.slice(1).map(line => {
        const cols = line.split(",").map(c => c.trim().replace(/^"|"$/g, ""));
        const firstName = cols[fnIdx] || "";
        const lastName = cols[lnIdx] || "";
        const email = emIdx >= 0 ? cols[emIdx] || "" : "";
        const phone = phIdx >= 0 ? cols[phIdx] || "" : "";

        let valid = true;
        let error = "";
        if (!firstName || !lastName) { valid = false; error = "Name required"; }
        if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { valid = false; error = "Invalid email"; }

        return { first_name: firstName, last_name: lastName, email, phone, valid, error };
      });

      setParsed(rows);
      setShowPreview(true);
    };
    reader.readAsText(file);
  };

  const importMutation = useMutation({
    mutationFn: async () => {
      const validRows = parsed.filter(r => r.valid);
      const res = await fetch(`/api/admin/companies/${companyId}/delegates/bulk`, {
        method: "POST",
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify({
          rows: validRows.map(r => ({
            company_id: companyId,
            first_name: r.first_name,
            last_name: r.last_name,
            email: r.email || null,
            phone: r.phone || null,
          })),
        }),
      });
      if (!res.ok) throw new Error("Import failed");
      return validRows.length;
    },
    onSuccess: (count) => {
      toast.success(`${count} delegate(s) imported successfully`);
      queryClient.invalidateQueries({ queryKey: ["portal-delegates"] });
      queryClient.invalidateQueries({ queryKey: ["compliance-delegates"] });
      queryClient.invalidateQueries({ queryKey: ["delegates"] });
      setParsed([]);
      setShowPreview(false);
      if (fileRef.current) fileRef.current.value = "";
    },
    onError: (err: Error) => {
      toast.error(err.message || "Import failed");
    },
  });

  const validCount = parsed.filter(r => r.valid).length;
  const invalidCount = parsed.filter(r => !r.valid).length;

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between">
        <CardTitle className="flex items-center gap-2 text-base">
          <FileSpreadsheet className="h-5 w-5" /> Bulk Import Delegates
        </CardTitle>
        {showPreview && (
          <Button variant="ghost" size="sm" onClick={() => { setShowPreview(false); setParsed([]); }}>
            <X className="h-4 w-4" />
          </Button>
        )}
      </CardHeader>
      <CardContent>
        {!showPreview ? (
          <div className="text-center py-6">
            <p className="text-sm text-muted-foreground mb-3">
              Upload a CSV file with columns: <code className="bg-muted px-1 rounded text-xs">first_name, last_name, email, phone</code>
            </p>
            <input ref={fileRef} type="file" accept=".csv" onChange={handleFile} className="hidden" />
            <Button variant="outline" onClick={() => fileRef.current?.click()}>
              <Upload className="h-4 w-4 mr-2" /> Select CSV File
            </Button>
          </div>
        ) : (
          <div className="space-y-4">
            <div className="flex items-center gap-4 text-sm">
              <span className="flex items-center gap-1 text-green-600">
                <CheckCircle2 className="h-4 w-4" /> {validCount} valid
              </span>
              {invalidCount > 0 && (
                <span className="flex items-center gap-1 text-red-600">
                  <AlertTriangle className="h-4 w-4" /> {invalidCount} invalid
                </span>
              )}
            </div>
            <div className="max-h-64 overflow-y-auto border rounded-lg">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>First Name</TableHead>
                    <TableHead>Last Name</TableHead>
                    <TableHead>Email</TableHead>
                    <TableHead>Phone</TableHead>
                    <TableHead>Status</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {parsed.map((row, i) => (
                    <TableRow key={i} className={!row.valid ? "bg-red-50 dark:bg-red-950/20" : ""}>
                      <TableCell className="text-sm">{row.first_name}</TableCell>
                      <TableCell className="text-sm">{row.last_name}</TableCell>
                      <TableCell className="text-sm">{row.email || "—"}</TableCell>
                      <TableCell className="text-sm">{row.phone || "—"}</TableCell>
                      <TableCell>
                        {row.valid ? (
                          <Badge variant="default" className="text-[10px]">Valid</Badge>
                        ) : (
                          <Badge variant="destructive" className="text-[10px]">{row.error}</Badge>
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => { setShowPreview(false); setParsed([]); }}>Cancel</Button>
              <Button
                onClick={() => importMutation.mutate()}
                disabled={validCount === 0 || importMutation.isPending}
              >
                {importMutation.isPending ? "Importing..." : `Import ${validCount} Delegate(s)`}
              </Button>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
};

export default BulkDelegateImport;
