import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { CreditCard, Plus, Search, MoreHorizontal, Edit, Trash2, Receipt } from "lucide-react";
import RecordImportButton from "@/components/RecordImportButton";
import ImportDialog from "@/components/ImportDialog";
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 { Dialog, DialogContent, DialogHeader, DialogTitle } 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 { Textarea } from "@/components/ui/textarea";
import UnitOwnerSelect from "@/components/UnitOwnerSelect";

const emptyForm = {
  amount: "",
  payment_method: "check",
  reference_number: "",
  payment_date: new Date().toISOString().split("T")[0],
  description: "",
  status: "completed",
  owner_id: "",
  association_id: "",
};

export default function PaymentsPage() {
  const { toast } = useToast();
  const [payments, setPayments] = useState<any[]>([]);
  const [associations, setAssociations] = useState<any[]>([]);
  const [owners, setOwners] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [importDialogOpen, setImportDialogOpen] = useState(false);
  const [chargeDialogOpen, setChargeDialogOpen] = useState(false);
  const [editingPayment, setEditingPayment] = useState<any>(null);
  const [form, setForm] = useState({ ...emptyForm });
  const [chargeForm, setChargeForm] = useState({
    owner_id: "",
    association_id: "",
    amount: "",
    date: new Date().toISOString().split("T")[0],
    transaction_type: "assessment",
    description: "",
  });
  const [saving, setSaving] = useState(false);

  const fetchData = async () => {
    setLoading(true);
    const [paymentsRes, assocRes, ownersRes] = await Promise.all([
      supabase.from("admin_payments").select("*, associations(name), owners(first_name, last_name)").order("created_at", { ascending: false }),
      supabase.from("associations").select("id, name").eq("status", "active").order("name"),
      supabase.from("owners").select("id, first_name, last_name, association_id, unit_id, units(unit_number)").eq("status", "active").order("last_name"),
    ]);
    if (paymentsRes.error) toast({ title: "Error", description: paymentsRes.error.message, variant: "destructive" });
    else setPayments(paymentsRes.data || []);
    setAssociations(assocRes.data || []);
    setOwners(ownersRes.data || []);
    setLoading(false);
  };

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

  const openAdd = () => {
    setEditingPayment(null);
    setForm({ ...emptyForm });
    setDialogOpen(true);
  };

  const openEdit = (payment: any) => {
    setEditingPayment(payment);
    setForm({
      amount: String(payment.amount || ""),
      payment_method: payment.payment_method || "check",
      reference_number: payment.reference_number || "",
      payment_date: payment.payment_date || "",
      description: payment.description || "",
      status: payment.status || "completed",
      owner_id: payment.owner_id || "",
      association_id: payment.association_id || "",
    });
    setDialogOpen(true);
  };

  const handleSave = async () => {
    if (!form.amount || !form.association_id) {
      toast({ title: "Amount and association are required", variant: "destructive" });
      return;
    }
    setSaving(true);
    const payload = {
      amount: parseFloat(form.amount) || 0,
      payment_method: form.payment_method,
      reference_number: form.reference_number || null,
      payment_date: form.payment_date || null,
      description: form.description || null,
      status: form.status,
      owner_id: form.owner_id || null,
      association_id: form.association_id,
    };

    if (editingPayment) {
      const { error } = await supabase.from("admin_payments").update(payload).eq("id", editingPayment.id);
      if (error) { toast({ title: "Error", description: error.message, variant: "destructive" }); setSaving(false); return; }
      toast({ title: "Payment updated" });
    } else {
      const { error } = await supabase.from("admin_payments").insert(payload).select("id").single();
      if (error) { toast({ title: "Error", description: error.message, variant: "destructive" }); setSaving(false); return; }
      toast({ title: "Payment recorded" });
    }
    setDialogOpen(false);
    setSaving(false);
    fetchData();
  };

  const handleNewCharge = async () => {
    if (!chargeForm.owner_id || !chargeForm.amount || !chargeForm.association_id) {
      toast({ title: "Owner, association, and amount are required", variant: "destructive" });
      return;
    }
    setSaving(true);
    const amount = parseFloat(chargeForm.amount) || 0;
    const owner = owners.find(o => o.id === chargeForm.owner_id);
    const { error } = await supabase.from("owner_ledger_entries").insert({
      owner_id: chargeForm.owner_id,
      association_id: chargeForm.association_id,
      unit_id: owner?.unit_id || null,
      date: chargeForm.date,
      transaction_type: chargeForm.transaction_type,
      description: chargeForm.description || `${chargeForm.transaction_type} charge`,
      debit: amount,
      credit: 0,
    });
    if (error) { toast({ title: "Error", description: error.message, variant: "destructive" }); setSaving(false); return; }

    // Update owner balance
    if (owner) {
      const { data: ownerData } = await supabase.from("owners").select("balance").eq("status", "active").eq("id", owner.id).maybeSingle();
      const newBalance = Number(ownerData?.balance || 0) + amount;
      await supabase.from("owners").update({ balance: newBalance }).eq("id", owner.id);
    }

    toast({ title: "Charge posted" });
    setChargeDialogOpen(false);
    setSaving(false);
    setChargeForm({ owner_id: "", association_id: "", amount: "", date: new Date().toISOString().split("T")[0], transaction_type: "assessment", description: "" });
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Delete this payment?")) return;
    await supabase.from("admin_payments").delete().eq("id", id);
    toast({ title: "Payment deleted" });
    fetchData();
  };

  const filtered = payments.filter((p) =>
    (p.description || "").toLowerCase().includes(search.toLowerCase()) ||
    (p.reference_number || "").toLowerCase().includes(search.toLowerCase()) ||
    (p.owners?.first_name || "").toLowerCase().includes(search.toLowerCase()) ||
    (p.owners?.last_name || "").toLowerCase().includes(search.toLowerCase())
  );

  const filteredOwners = form.association_id
    ? owners.filter(o => o.association_id === form.association_id)
    : owners;

  const filteredChargeOwners = chargeForm.association_id
    ? owners.filter(o => o.association_id === chargeForm.association_id)
    : owners;

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <CreditCard className="h-6 w-6 text-primary" /> Payments
          </h1>
          <p className="text-sm text-muted-foreground mt-1">Process and track homeowner payments and charges.</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" className="gap-2" onClick={() => setImportDialogOpen(true)}>
            <CreditCard className="h-4 w-4" /> Lockbox Import
          </Button>
          <RecordImportButton
            title="Import Payments"
            description="Upload a CSV or Excel file with payment records."
            expectedColumns={[
              { key: "amount", label: "Amount", required: true },
              { key: "payment_method", label: "Payment Method" },
              { key: "reference_number", label: "Reference Number" },
              { key: "payment_date", label: "Payment Date" },
              { key: "description", label: "Description" },
            ]}
            onImport={async (rows) => {
              const assocId = associations[0]?.id;
              if (!assocId) throw new Error("Create an association first");
              const payload = rows.map(r => ({
                amount: parseFloat(r.amount) || 0,
                payment_method: r.payment_method || "check",
                reference_number: r.reference_number || null,
                payment_date: r.payment_date || new Date().toISOString().split("T")[0],
                description: r.description || null,
                association_id: assocId,
              }));
              const { error } = await supabase.from("admin_payments").insert(payload);
              if (error) throw error;
              toast({ title: `Imported ${rows.length} payments` });
              fetchData();
            }}
            templateFileName="payments_template.xlsx"
          />
          <Button variant="outline" className="gap-2" onClick={() => setChargeDialogOpen(true)}>
            <Receipt className="h-4 w-4" /> New Charge
          </Button>
          <Button className="gap-2" onClick={openAdd}>
            <Plus className="h-4 w-4" /> Record Payment
          </Button>
        </div>
      </div>

      <ImportDialog open={importDialogOpen} onOpenChange={setImportDialogOpen} onSuccess={fetchData} defaultFileType="lockbox" />

      <div className="relative max-w-md">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input placeholder="Search payments..." className="pl-10" value={search} onChange={(e) => setSearch(e.target.value)} />
      </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 payments found.</CardContent>
        </Card>
      ) : (
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Owner</TableHead>
                <TableHead>Amount</TableHead>
                <TableHead>Method</TableHead>
                <TableHead>Reference</TableHead>
                <TableHead>Date</TableHead>
                <TableHead>Description</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="w-12" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map((p) => (
                <TableRow key={p.id}>
                  <TableCell>{p.owners ? `${p.owners.first_name} ${p.owners.last_name}` : "—"}</TableCell>
                  <TableCell className="font-medium">${Number(p.amount).toLocaleString()}</TableCell>
                  <TableCell className="capitalize">{p.payment_method}</TableCell>
                  <TableCell>{p.reference_number || "—"}</TableCell>
                  <TableCell>{p.payment_date || "—"}</TableCell>
                  <TableCell>{p.description || "—"}</TableCell>
                  <TableCell>
                    <Badge variant={p.status === "completed" ? "default" : "secondary"}>{p.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(p)}>
                          <Edit className="h-4 w-4 mr-2" /> Edit
                        </DropdownMenuItem>
                        <DropdownMenuItem className="text-destructive" onClick={() => handleDelete(p.id)}>
                          <Trash2 className="h-4 w-4 mr-2" /> Delete
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      )}

      {/* Record / Edit Payment Dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>{editingPayment ? "Edit Payment" : "Record Payment"}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Association *</Label>
                <Select value={form.association_id} onValueChange={(v) => setForm({ ...form, association_id: v, owner_id: "" })}>
                  <SelectTrigger><SelectValue placeholder="Select association" /></SelectTrigger>
                  <SelectContent>
                    {associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Owner</Label>
                <UnitOwnerSelect
                  owners={owners}
                  value={form.owner_id}
                  onValueChange={(v) => setForm({ ...form, owner_id: v })}
                  associationId={form.association_id}
                  placeholder="Select owner"
                />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Amount *</Label>
                <Input type="number" step="0.01" value={form.amount} onChange={(e) => setForm({ ...form, amount: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>Method</Label>
                <Select value={form.payment_method} onValueChange={(v) => setForm({ ...form, payment_method: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="check">Check</SelectItem>
                    <SelectItem value="ach">ACH</SelectItem>
                    <SelectItem value="credit_card">Credit Card</SelectItem>
                    <SelectItem value="cash">Cash</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Reference #</Label>
                <Input value={form.reference_number} onChange={(e) => setForm({ ...form, reference_number: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>Date</Label>
                <Input type="date" value={form.payment_date} onChange={(e) => setForm({ ...form, payment_date: e.target.value })} />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Status</Label>
                <Select value={form.status} onValueChange={(v) => setForm({ ...form, status: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="completed">Completed</SelectItem>
                    <SelectItem value="pending">Pending</SelectItem>
                    <SelectItem value="voided">Voided</SelectItem>
                    <SelectItem value="refunded">Refunded</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} rows={2} />
            </div>
          </div>
          <div className="flex justify-end gap-2 pt-4">
            <Button variant="outline" onClick={() => setDialogOpen(false)}>Cancel</Button>
            <Button onClick={handleSave} disabled={saving}>
              {saving ? "Saving..." : editingPayment ? "Update" : "Record"}
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* New Charge Dialog */}
      <Dialog open={chargeDialogOpen} onOpenChange={setChargeDialogOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>New Charge / Assessment</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Association *</Label>
                <Select value={chargeForm.association_id} onValueChange={(v) => setChargeForm({ ...chargeForm, association_id: v, owner_id: "" })}>
                  <SelectTrigger><SelectValue placeholder="Select association" /></SelectTrigger>
                  <SelectContent>
                    {associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Owner *</Label>
                <UnitOwnerSelect
                  owners={owners}
                  value={chargeForm.owner_id}
                  onValueChange={(v) => setChargeForm({ ...chargeForm, owner_id: v })}
                  associationId={chargeForm.association_id}
                  placeholder="Select owner"
                />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Amount *</Label>
                <Input type="number" step="0.01" value={chargeForm.amount} onChange={(e) => setChargeForm({ ...chargeForm, amount: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>Type</Label>
                <Select value={chargeForm.transaction_type} onValueChange={(v) => setChargeForm({ ...chargeForm, transaction_type: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="assessment">Assessment</SelectItem>
                    <SelectItem value="late_fee">Late Fee</SelectItem>
                    <SelectItem value="violation_fine">Violation Fine</SelectItem>
                    <SelectItem value="admin_fee">Admin Fee</SelectItem>
                    <SelectItem value="interest">Interest</SelectItem>
                    <SelectItem value="legal_fee">Legal Fee</SelectItem>
                    <SelectItem value="other">Other</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="space-y-2">
              <Label>Date</Label>
              <Input type="date" value={chargeForm.date} onChange={(e) => setChargeForm({ ...chargeForm, date: e.target.value })} />
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Textarea value={chargeForm.description} onChange={(e) => setChargeForm({ ...chargeForm, description: e.target.value })} rows={2} />
            </div>
          </div>
          <div className="flex justify-end gap-2 pt-4">
            <Button variant="outline" onClick={() => setChargeDialogOpen(false)}>Cancel</Button>
            <Button onClick={handleNewCharge} disabled={saving}>
              {saving ? "Posting..." : "Post Charge"}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
