import { useState, useEffect, useMemo } from "react";
import { Textarea } from "@/components/ui/textarea";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { PenLine, Plus, Search, MoreHorizontal, Edit, Trash2, RotateCcw, Printer, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { downloadChecksPdf, type CheckData } from "@/utils/checkPdfGenerator";

const statusColors: Record<string, string> = {
  draft: "bg-muted text-muted-foreground",
  pending: "bg-amber-100 text-amber-700",
  printed: "bg-blue-100 text-blue-700",
  cleared: "bg-emerald-100 text-emerald-700",
  void: "bg-red-100 text-red-700",
};

export default function CompanyChecksPage() {
  const { toast } = useToast();
  const [tab, setTab] = useState("write");

  // Shared
  const [bankAccounts, setBankAccounts] = useState<any[]>([]);
  const [checks, setChecks] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  // Write tab
  const [search, setSearch] = useState("");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [form, setForm] = useState({
    payee: "",
    payee_address: "",
    amount: "",
    check_number: "",
    memo: "",
    check_date: new Date().toISOString().split("T")[0],
    status: "draft",
    company_bank_account_id: "",
  });

  // Print tab
  const [printAccountId, setPrintAccountId] = useState<string>("");
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [printing, setPrinting] = useState(false);

  const fetchData = async () => {
    setLoading(true);
    const [{ data: checksData }, { data: banksData }] = await Promise.all([
      supabase
        .from("company_checks")
        .select("*, company_bank_accounts(account_name, bank_name)")
        .order("created_at", { ascending: false }),
      supabase
        .from("company_bank_accounts")
        .select("*")
        .eq("status", "active")
        .order("account_name"),
    ]);
    setChecks(checksData || []);
    setBankAccounts(banksData || []);
    if (!printAccountId && banksData && banksData.length > 0) {
      setPrintAccountId(banksData[0].id);
    }
    setLoading(false);
  };

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

  /* ---------------- Write tab ---------------- */
  const openNew = () => {
    setEditing(null);
    setForm({
      payee: "",
      payee_address: "",
      amount: "",
      check_number: "",
      memo: "",
      check_date: new Date().toISOString().split("T")[0],
      status: "draft",
      company_bank_account_id: bankAccounts[0]?.id || "",
    });
    setDialogOpen(true);
  };

  const openEdit = (c: any) => {
    setEditing(c);
    setForm({
      payee: c.payee || "",
      payee_address: c.payee_address || "",
      amount: c.amount?.toString() || "",
      check_number: c.check_number || "",
      memo: c.memo || "",
      check_date: c.check_date || "",
      status: c.status,
      company_bank_account_id: c.company_bank_account_id || "",
    });
    setDialogOpen(true);
  };

  const handleSave = async () => {
    if (!form.payee.trim()) {
      toast({ variant: "destructive", title: "Payee is required" });
      return;
    }
    if (!form.company_bank_account_id) {
      toast({ variant: "destructive", title: "Select a bank account" });
      return;
    }
    const { data: { user } } = await supabase.auth.getUser();
    const payload = {
      payee: form.payee.trim(),
      payee_address: form.payee_address.trim() || null,
      amount: parseFloat(form.amount) || 0,
      check_number: form.check_number || null,
      memo: form.memo || null,
      check_date: form.check_date || null,
      status: form.status,
      company_bank_account_id: form.company_bank_account_id,
      created_by: user?.id,
    };
    const { error } = editing
      ? await supabase.from("company_checks").update(payload).eq("id", editing.id)
      : await supabase.from("company_checks").insert(payload);
    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message });
      return;
    }
    toast({ title: editing ? "Check updated" : "Check created" });
    setDialogOpen(false);
    fetchData();
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Delete this check?")) return;
    const { error } = await supabase.from("company_checks").delete().eq("id", id);
    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message });
      return;
    }
    toast({ title: "Deleted" });
    fetchData();
  };

  const markUnpaid = async (c: any) => {
    await supabase.from("company_checks").update({ status: "draft", printed: false }).eq("id", c.id);
    await supabase.from("company_bank_transactions").delete().eq("check_id", c.id);
    toast({ title: "Check marked unpaid" });
    fetchData();
  };

  const filtered = checks.filter((c) => (c.payee || "").toLowerCase().includes(search.toLowerCase()));

  /* ---------------- Print tab ---------------- */
  const printableChecks = useMemo(
    () => checks.filter((c) =>
      ["draft", "pending"].includes(c.status) &&
      !c.printed &&
      (printAccountId ? c.company_bank_account_id === printAccountId : true)
    ),
    [checks, printAccountId]
  );

  const selectedBank = bankAccounts.find((b) => b.id === printAccountId);

  const toggleSelect = (id: string) => {
    const s = new Set(selected);
    if (s.has(id)) s.delete(id); else s.add(id);
    setSelected(s);
  };

  const selectAll = () => {
    if (selected.size === printableChecks.length) setSelected(new Set());
    else setSelected(new Set(printableChecks.map((c) => c.id)));
  };

  const handlePrint = async () => {
    if (selected.size === 0) {
      toast({ variant: "destructive", title: "Select checks to print" });
      return;
    }
    if (!selectedBank) {
      toast({ variant: "destructive", title: "Select a bank account" });
      return;
    }
    setPrinting(true);
    try {
      const selectedChecks = printableChecks.filter((c) => selected.has(c.id));
      let nextNum = selectedBank.next_check_number || 1001;

      // Load saved company check layout (single row, shared for the management company)
      const { data: layoutRow } = await supabase
        .from("company_check_layouts" as any)
        .select("*")
        .maybeSingle();

      const layout: any = layoutRow
        ? {
            ...(layoutRow as any),
            payer_name: (layoutRow as any).payer_name || selectedBank.account_name,
          }
        : {
            check_position: "top",
            show_field_labels: true,
            show_payer_block: true,
            show_signature_line: true,
            payer_name: selectedBank.account_name,
          };

      const checksForPdf: CheckData[] = selectedChecks.map((c) => {
        const num = c.check_number || String(nextNum++);
        return {
          check_number: num,
          check_date: c.check_date || new Date().toISOString().split("T")[0],
          payee: c.payee,
          payee_address: c.payee_address || null,
          amount: Number(c.amount) || 0,
          memo: c.memo || "",
          bank_account_name: selectedBank.account_name,
          bank_routing_number: selectedBank.routing_number || "",
          bank_account_number: selectedBank.account_number || "",
          association_name: selectedBank.account_name,
          layout,
        };
      });

      await downloadChecksPdf(
        checksForPdf,
        `company-checks-${new Date().toISOString().split("T")[0]}.pdf`,
        { includeMicr: true }
      );

      // Update checks: assign numbers, mark printed, create register entries
      let assignNum = selectedBank.next_check_number || 1001;
      for (const c of selectedChecks) {
        const checkNo = c.check_number || String(assignNum++);
        await supabase.from("company_checks")
          .update({ check_number: checkNo, status: "printed", printed: true })
          .eq("id", c.id);

        await supabase.from("company_bank_transactions").insert({
          date: c.check_date || new Date().toISOString().split("T")[0],
          transaction_type: "check",
          description: `Check #${checkNo} to ${c.payee}${c.memo ? ` — ${c.memo}` : ""}`,
          reference_number: checkNo,
          debit: Number(c.amount) || 0,
          credit: 0,
          company_bank_account_id: selectedBank.id,
          check_id: c.id,
        });
      }

      // Bump next check number
      await supabase.from("company_bank_accounts")
        .update({ next_check_number: assignNum })
        .eq("id", selectedBank.id);

      toast({ title: `Printed ${selectedChecks.length} check(s)` });
      setSelected(new Set());
      fetchData();
    } catch (err: any) {
      toast({ variant: "destructive", title: "Print error", description: err.message });
    }
    setPrinting(false);
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
          <PenLine className="h-6 w-6 text-primary" /> Company Checks
        </h1>
        <p className="text-sm text-muted-foreground mt-1">
          Write and print checks from the management company's own bank accounts.
        </p>
      </div>

      <Tabs value={tab} onValueChange={setTab}>
        <TabsList>
          <TabsTrigger value="write">Write Checks</TabsTrigger>
          <TabsTrigger value="print">Print Checks</TabsTrigger>
        </TabsList>

        {/* Write tab */}
        <TabsContent value="write" className="space-y-4 mt-4">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <div className="relative max-w-md flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input placeholder="Search payees..." className="pl-10" value={search} onChange={(e) => setSearch(e.target.value)} />
            </div>
            <Button className="gap-2" onClick={openNew}>
              <Plus className="h-4 w-4" /> Write Check
            </Button>
          </div>

          {loading ? (
            <div className="flex justify-center py-12">
              <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
            </div>
          ) : filtered.length === 0 ? (
            <Card><CardContent className="py-12 text-center text-muted-foreground">No checks yet.</CardContent></Card>
          ) : (
            <Card>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Check #</TableHead>
                    <TableHead>Payee</TableHead>
                    <TableHead>Account</TableHead>
                    <TableHead className="text-right">Amount</TableHead>
                    <TableHead>Date</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="w-12" />
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filtered.map((c) => (
                    <TableRow key={c.id}>
                      <TableCell>{c.check_number || "—"}</TableCell>
                      <TableCell className="font-medium">{c.payee}</TableCell>
                      <TableCell className="text-sm text-muted-foreground">
                        {c.company_bank_accounts?.account_name || "—"}
                      </TableCell>
                      <TableCell className="text-right">${Number(c.amount).toLocaleString("en-US", { minimumFractionDigits: 2 })}</TableCell>
                      <TableCell>{c.check_date || "—"}</TableCell>
                      <TableCell>
                        <Badge className={statusColors[c.status] || "bg-muted text-muted-foreground"}>{c.status}</Badge>
                      </TableCell>
                      <TableCell>
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="icon" className="h-8 w-8"><MoreHorizontal className="h-4 w-4" /></Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuItem onClick={() => openEdit(c)}>
                              <Edit className="h-4 w-4 mr-2" /> Edit
                            </DropdownMenuItem>
                            {(c.status === "printed" || c.status === "cleared" || c.status === "pending") && (
                              <DropdownMenuItem onClick={() => markUnpaid(c)}>
                                <RotateCcw className="h-4 w-4 mr-2" /> Mark Unpaid
                              </DropdownMenuItem>
                            )}
                            <DropdownMenuItem className="text-destructive" onClick={() => handleDelete(c.id)}>
                              <Trash2 className="h-4 w-4 mr-2" /> Delete
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </Card>
          )}
        </TabsContent>

        {/* Print tab */}
        <TabsContent value="print" className="space-y-4 mt-4">
          <Card>
            <CardContent className="p-4 space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <Label>Bank Account</Label>
                  <Select value={printAccountId} onValueChange={setPrintAccountId}>
                    <SelectTrigger><SelectValue placeholder="Select bank account" /></SelectTrigger>
                    <SelectContent>
                      {bankAccounts.map((b) => (
                        <SelectItem key={b.id} value={b.id}>
                          {b.account_name}{b.bank_name ? ` — ${b.bank_name}` : ""}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="flex items-end">
                  <Button className="gap-2 w-full sm:w-auto" onClick={handlePrint} disabled={printing || selected.size === 0}>
                    <Printer className="h-4 w-4" />
                    {printing ? "Printing..." : `Print ${selected.size} Check(s)`}
                  </Button>
                </div>
              </div>

              {selectedBank && (
                <div className="text-sm text-muted-foreground">
                  Next check #: <span className="font-medium text-foreground">{selectedBank.next_check_number}</span>
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-10">
                    <Checkbox
                      checked={selected.size > 0 && selected.size === printableChecks.length}
                      onCheckedChange={selectAll}
                    />
                  </TableHead>
                  <TableHead>Payee</TableHead>
                  <TableHead className="text-right">Amount</TableHead>
                  <TableHead>Date</TableHead>
                  <TableHead>Memo</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow><TableCell colSpan={5} className="text-center py-8 text-muted-foreground">Loading...</TableCell></TableRow>
                ) : printableChecks.length === 0 ? (
                  <TableRow><TableCell colSpan={5} className="text-center py-8 text-muted-foreground">No unprinted checks for this account.</TableCell></TableRow>
                ) : printableChecks.map((c) => (
                  <TableRow key={c.id}>
                    <TableCell>
                      <Checkbox checked={selected.has(c.id)} onCheckedChange={() => toggleSelect(c.id)} />
                    </TableCell>
                    <TableCell className="font-medium">{c.payee}</TableCell>
                    <TableCell className="text-right">${Number(c.amount).toLocaleString("en-US", { minimumFractionDigits: 2 })}</TableCell>
                    <TableCell>{c.check_date || "—"}</TableCell>
                    <TableCell className="text-sm text-muted-foreground max-w-xs truncate">{c.memo || "—"}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Write/Edit dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{editing ? "Edit" : "Write"} Company Check</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Bank Account *</Label>
              <Select value={form.company_bank_account_id} onValueChange={(v) => setForm({ ...form, company_bank_account_id: v })}>
                <SelectTrigger><SelectValue placeholder="Select bank account" /></SelectTrigger>
                <SelectContent>
                  {bankAccounts.map((b) => (
                    <SelectItem key={b.id} value={b.id}>
                      {b.account_name}{b.bank_name ? ` — ${b.bank_name}` : ""}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Payee *</Label>
                <Input value={form.payee} onChange={(e) => setForm({ ...form, payee: e.target.value })} />
              </div>
              <div>
                <Label>Check #</Label>
                <Input value={form.check_number} onChange={(e) => setForm({ ...form, check_number: e.target.value })} placeholder="Auto-assigned on print" />
              </div>
            </div>
            <div>
              <Label>Payee Address</Label>
              <Textarea
                rows={2}
                placeholder="123 Main St&#10;City, ST 12345"
                value={form.payee_address}
                onChange={(e) => setForm({ ...form, payee_address: e.target.value })}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Amount</Label>
                <Input type="number" step="0.01" value={form.amount} onChange={(e) => setForm({ ...form, amount: e.target.value })} />
              </div>
              <div>
                <Label>Date</Label>
                <Input type="date" value={form.check_date} onChange={(e) => setForm({ ...form, check_date: e.target.value })} />
              </div>
            </div>
            <div>
              <Label>Memo</Label>
              <Input value={form.memo} onChange={(e) => setForm({ ...form, memo: e.target.value })} />
            </div>
            <div>
              <Label>Status</Label>
              <Select value={form.status} onValueChange={(v) => setForm({ ...form, status: v })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="draft">Draft</SelectItem>
                  <SelectItem value="pending">Pending</SelectItem>
                  <SelectItem value="printed">Printed</SelectItem>
                  <SelectItem value="cleared">Cleared</SelectItem>
                  <SelectItem value="void">Void</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)}>Cancel</Button>
            <Button onClick={handleSave}>{editing ? "Update" : "Create"}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
