import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription,
} from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Loader2, Plus, Edit2, Trash2, Search, AlertTriangle, CreditCard } from "lucide-react";

interface Association { id: string; name: string; }

interface StripeMapping {
  id: string; association_id: string | null; stripe_account_id: string;
  stripe_public_key: string; stripe_secret_key: string | null;
  is_active: boolean; pass_processing_fee: boolean;
  processing_fee_percent: number; processing_fee_fixed_cents: number;
  label: string | null; associations?: { name: string } | null;
}

const emptyStripeForm = {
  association_id: "", stripe_account_id: "", stripe_public_key: "", stripe_secret_key: "",
  is_active: true, pass_processing_fee: false, processing_fee_percent: 0.029,
  processing_fee_fixed_cents: 30, label: "",
};

export default function AdminStripeAccountsPage() {
  const { toast } = useToast();
  const [associations, setAssociations] = useState<Association[]>([]);
  const [stripeMappings, setStripeMappings] = useState<StripeMapping[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");

  const [stripeModalOpen, setStripeModalOpen] = useState(false);
  const [editingStripe, setEditingStripe] = useState<StripeMapping | null>(null);
  const [stripeForm, setStripeForm] = useState(emptyStripeForm);
  const [stripeSaving, setStripeSaving] = useState(false);

  const [isDeleting, setIsDeleting] = useState(false);

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

  const fetchData = async () => {
    setLoading(true);
    try {
      const [assocRes, stripeRes] = await Promise.all([
        supabase.from("associations").select("id, name").eq("status", "active").order("name"),
        supabase.from("stripe_account_mappings").select("*, associations(name)").order("created_at"),
      ]);
      if (assocRes.error) throw assocRes.error;
      setAssociations(assocRes.data || []);
      setStripeMappings((stripeRes.data as any) || []);
    } catch {
      toast({ title: "Error", description: "Failed to load payment gateway data.", variant: "destructive" });
    } finally {
      setLoading(false);
    }
  };

  const openStripeModal = (m: StripeMapping | null = null) => {
    if (m) {
      setEditingStripe(m);
      setStripeForm({
        association_id: m.association_id || "", stripe_account_id: m.stripe_account_id,
        stripe_public_key: m.stripe_public_key, stripe_secret_key: m.stripe_secret_key || "",
        is_active: m.is_active, pass_processing_fee: m.pass_processing_fee,
        processing_fee_percent: m.processing_fee_percent,
        processing_fee_fixed_cents: m.processing_fee_fixed_cents, label: m.label || "",
      });
    } else { setEditingStripe(null); setStripeForm({ ...emptyStripeForm }); }
    setStripeModalOpen(true);
  };

  const saveStripe = async () => {
    if (!stripeForm.stripe_account_id || !stripeForm.stripe_public_key) {
      toast({ title: "Validation Error", description: "Fill in Stripe Account ID and Public Key.", variant: "destructive" }); return;
    }
    if (!stripeForm.association_id && !stripeForm.label) {
      toast({ title: "Validation Error", description: "Select an association or provide a label.", variant: "destructive" }); return;
    }
    setStripeSaving(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      const payload: any = {
        association_id: stripeForm.association_id || null, stripe_account_id: stripeForm.stripe_account_id,
        stripe_public_key: stripeForm.stripe_public_key, stripe_secret_key: stripeForm.stripe_secret_key || null,
        is_active: stripeForm.is_active, pass_processing_fee: stripeForm.pass_processing_fee,
        processing_fee_percent: stripeForm.processing_fee_percent,
        processing_fee_fixed_cents: stripeForm.processing_fee_fixed_cents, label: stripeForm.label || null,
      };
      if (editingStripe) {
        const { error } = await supabase.from("stripe_account_mappings").update(payload).eq("id", editingStripe.id);
        if (error) throw error;
      } else {
        payload.created_by = user?.id;
        const { error } = await supabase.from("stripe_account_mappings").insert(payload);
        if (error) throw error;
      }
      toast({ title: "Success", description: `Stripe mapping ${editingStripe ? "updated" : "created"}.` });
      setStripeModalOpen(false); fetchData();
    } catch (e: any) {
      toast({ title: "Error", description: e.message || "Failed to save.", variant: "destructive" });
    } finally { setStripeSaving(false); }
  };

  const deleteStripe = async (id: string) => {
    if (!window.confirm("Delete this Stripe mapping?")) return;
    setIsDeleting(true);
    try {
      const { error } = await supabase.from("stripe_account_mappings").delete().eq("id", id);
      if (error) throw error;
      toast({ title: "Deleted" }); fetchData();
    } catch { toast({ title: "Error", description: "Failed to delete.", variant: "destructive" }); }
    finally { setIsDeleting(false); }
  };

  const filteredAssociations = associations.filter((a) =>
    a.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const getStripeForAssoc = (id: string) => stripeMappings.find(m => m.association_id === id);

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <CreditCard className="h-6 w-6 text-primary" />
            Payment Gateways
          </h1>
          <p className="text-muted-foreground mt-1 text-sm">
            Configure Stripe payment processing per association.
          </p>
        </div>
        <Button onClick={() => openStripeModal()}>
          <Plus className="w-4 h-4 mr-2" /> Add Stripe Account
        </Button>
      </div>

      <Card>
        <CardHeader className="pb-4">
          <div className="flex items-center relative max-w-md">
            <Search className="w-4 h-4 absolute left-3 text-muted-foreground" />
            <Input placeholder="Search associations..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="pl-9" />
          </div>
        </CardHeader>
        <CardContent className="p-0">
          {loading ? (
            <div className="p-12 flex justify-center"><Loader2 className="h-8 w-8 animate-spin text-primary" /></div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="font-semibold">Account</TableHead>
                  <TableHead className="font-semibold">Stripe Account ID</TableHead>
                  <TableHead className="font-semibold">Fee Pass-through</TableHead>
                  <TableHead className="font-semibold">Status</TableHead>
                  <TableHead className="text-right font-semibold">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {stripeMappings.filter(m => !m.association_id).map(m => (
                  <TableRow key={m.id}>
                    <TableCell className="font-medium">
                      <div className="flex items-center gap-2">
                        <Badge variant="outline" className="text-2xs">Company</Badge>
                        {m.label || "Company Account"}
                      </div>
                    </TableCell>
                    <TableCell className="font-mono text-sm text-muted-foreground">{m.stripe_account_id}</TableCell>
                    <TableCell><Badge variant={m.pass_processing_fee ? "default" : "secondary"}>{m.pass_processing_fee ? "Yes" : "No"}</Badge></TableCell>
                    <TableCell><Badge variant={m.is_active ? "default" : "secondary"}>{m.is_active ? "Active" : "Inactive"}</Badge></TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button variant="ghost" size="icon" onClick={() => openStripeModal(m)} className="h-8 w-8"><Edit2 className="w-4 h-4" /></Button>
                        <Button variant="ghost" size="icon" onClick={() => deleteStripe(m.id)} disabled={isDeleting} className="h-8 w-8 text-destructive hover:text-destructive"><Trash2 className="w-4 h-4" /></Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
                {filteredAssociations.map(assoc => {
                  const m = getStripeForAssoc(assoc.id);
                  return (
                    <TableRow key={assoc.id}>
                      <TableCell className="font-medium">
                        {assoc.name}
                        {!m && <div className="flex items-center text-warning text-xs mt-1"><AlertTriangle className="w-3 h-3 mr-1" /> No Stripe account</div>}
                      </TableCell>
                      <TableCell className="font-mono text-sm text-muted-foreground">{m ? m.stripe_account_id : "—"}</TableCell>
                      <TableCell>{m ? <Badge variant={m.pass_processing_fee ? "default" : "secondary"}>{m.pass_processing_fee ? "Yes" : "No"}</Badge> : "—"}</TableCell>
                      <TableCell>{m ? <Badge variant={m.is_active ? "default" : "secondary"}>{m.is_active ? "Active" : "Inactive"}</Badge> : <Badge variant="outline">Unconfigured</Badge>}</TableCell>
                      <TableCell className="text-right">
                        {m ? (
                          <div className="flex justify-end gap-2">
                            <Button variant="ghost" size="icon" onClick={() => openStripeModal(m)} className="h-8 w-8"><Edit2 className="w-4 h-4" /></Button>
                            <Button variant="ghost" size="icon" onClick={() => deleteStripe(m.id)} disabled={isDeleting} className="h-8 w-8 text-destructive hover:text-destructive"><Trash2 className="w-4 h-4" /></Button>
                          </div>
                        ) : (
                          <Button variant="outline" size="sm" onClick={() => { setEditingStripe(null); setStripeForm({ ...emptyStripeForm, association_id: assoc.id }); setStripeModalOpen(true); }}>Assign</Button>
                        )}
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      <Dialog open={stripeModalOpen} onOpenChange={setStripeModalOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>{editingStripe ? "Edit Stripe Assignment" : "Add Stripe Assignment"}</DialogTitle>
            <DialogDescription>Configure Stripe account details for the association.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Account Label <span className="text-muted-foreground text-xs">(for company accounts)</span></Label>
              <Input placeholder="e.g. Avria Community Management, LLC" value={stripeForm.label} onChange={e => setStripeForm(p => ({ ...p, label: e.target.value }))} />
            </div>
            <div className="space-y-2">
              <Label>Association</Label>
              <Select value={stripeForm.association_id} onValueChange={v => setStripeForm(p => ({ ...p, association_id: v === "__none__" ? "" : v }))} disabled={!!editingStripe}>
                <SelectTrigger><SelectValue placeholder="Select association..." /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__none__">— No Association (Company) —</SelectItem>
                  {associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Stripe Account ID <span className="text-destructive">*</span></Label>
              <Input placeholder="acct_123456789" value={stripeForm.stripe_account_id} onChange={e => setStripeForm(p => ({ ...p, stripe_account_id: e.target.value }))} className="font-mono" />
            </div>
            <div className="space-y-2">
              <Label>Stripe Public Key <span className="text-destructive">*</span></Label>
              <Input placeholder="pk_live_..." value={stripeForm.stripe_public_key} onChange={e => setStripeForm(p => ({ ...p, stripe_public_key: e.target.value }))} className="font-mono" />
            </div>
            <div className="space-y-2">
              <Label>Stripe Secret Key</Label>
              <Input type="password" placeholder="sk_live_..." value={stripeForm.stripe_secret_key} onChange={e => setStripeForm(p => ({ ...p, stripe_secret_key: e.target.value }))} className="font-mono" />
            </div>
            <div className="flex items-center justify-between pt-2">
              <Label>Active</Label>
              <Switch checked={stripeForm.is_active} onCheckedChange={c => setStripeForm(p => ({ ...p, is_active: c }))} />
            </div>
            <div className="flex items-center justify-between">
              <Label>Pass Processing Fee to Homeowner</Label>
              <Switch checked={stripeForm.pass_processing_fee} onCheckedChange={c => setStripeForm(p => ({ ...p, pass_processing_fee: c }))} />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setStripeModalOpen(false)} disabled={stripeSaving}>Cancel</Button>
            <Button onClick={saveStripe} disabled={stripeSaving}>
              {stripeSaving ? <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Saving...</> : "Save"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
