import { useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { FileSpreadsheet, Upload, Loader2, CheckCircle2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";

export default function ImportTransactionsPage() {
  const { toast } = useToast();
  const [csvText, setCsvText] = useState("");
  const [parsed, setParsed] = useState<any[]>([]);
  const [importing, setImporting] = useState(false);
  const [imported, setImported] = useState(false);

  const handleParse = () => {
    const lines = csvText.trim().split("\n").filter(Boolean);
    if (lines.length < 2) { toast({ title: "Need header + data rows", variant: "destructive" }); return; }
    const headers = lines[0].split(",").map((h) => h.trim().toLowerCase());
    const rows = lines.slice(1).map((line) => {
      const cols = line.split(",").map((c) => c.trim());
      const obj: any = {};
      headers.forEach((h, i) => { obj[h] = cols[i] || ""; });
      return obj;
    });
    setParsed(rows);
    toast({ title: `Parsed ${rows.length} transactions` });
  };

  const handleImport = async () => {
    setImporting(true);
    const { data: a } = await supabase.from("associations").select("id").eq("status", "active").limit(1);
    if (!a?.length) { toast({ title: "Create an association first", variant: "destructive" }); setImporting(false); return; }
    const entries = parsed.map((row) => ({
      association_id: a[0].id,
      date: row.date || new Date().toISOString().split("T")[0],
      description: row.description || row.memo || "",
      amount: parseFloat(row.amount) || 0,
      type: parseFloat(row.amount) >= 0 ? "credit" : "debit",
    }));
    const { error } = await supabase.from("journal_entries").insert(entries);
    if (error) toast({ title: "Error", description: error.message, variant: "destructive" });
    else { toast({ title: `${entries.length} transactions imported!` }); setImported(true); }
    setImporting(false);
  };

  return (
    <div className="space-y-6 max-w-4xl">
      <div><h1 className="text-2xl font-bold text-foreground flex items-center gap-2"><FileSpreadsheet className="h-6 w-6 text-primary" /> Import Transactions</h1><p className="text-sm text-muted-foreground mt-1">Import bank transactions from CSV data.</p></div>

      <Card>
        <CardHeader><CardTitle>Paste CSV Data</CardTitle><CardDescription>Include a header row with columns: date, description, amount</CardDescription></CardHeader>
        <CardContent className="space-y-4">
          <Textarea placeholder={"date,description,amount\n2025-01-15,Landscaping Payment,-1500.00\n2025-01-20,Assessment Collection,3200.00"} value={csvText} onChange={(e) => { setCsvText(e.target.value); setParsed([]); setImported(false); }} rows={8} />
          <Button onClick={handleParse} className="gap-2"><Upload className="h-4 w-4" /> Parse CSV</Button>
        </CardContent>
      </Card>

      {parsed.length > 0 && (
        <Card>
          <CardHeader><CardTitle>Preview ({parsed.length} rows)</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            <Table><TableHeader><TableRow>{Object.keys(parsed[0]).map((k) => <TableHead key={k} className="capitalize">{k}</TableHead>)}</TableRow></TableHeader><TableBody>
              {parsed.slice(0, 10).map((row, i) => (<TableRow key={i}>{Object.values(row).map((v: any, j) => <TableCell key={j}>{v}</TableCell>)}</TableRow>))}
            </TableBody></Table>
            {parsed.length > 10 && <p className="text-sm text-muted-foreground">... and {parsed.length - 10} more rows</p>}
            {imported ? (
              <div className="flex items-center gap-2 text-emerald-600"><CheckCircle2 className="h-5 w-5" /> Successfully imported!</div>
            ) : (
              <Button onClick={handleImport} disabled={importing} className="gap-2">{importing ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}{importing ? "Importing..." : "Import All"}</Button>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  );
}
