import { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Card } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Landmark } from "lucide-react";
import BankAccountsPage from "@/pages/BankAccountsPage";
import CheckLayoutEditor from "@/components/CheckLayoutEditor";
import { supabase } from "@/integrations/supabase/client";

type AssocOpt = { id: string; name: string };

export default function BankAccountsHubPage() {
  const [params, setParams] = useSearchParams();
  const tab = params.get("tab") === "check-settings" ? "check-settings" : "accounts";
  const [associations, setAssociations] = useState<AssocOpt[]>([]);
  const [selectedId, setSelectedId] = useState<string>(() => localStorage.getItem("checkSettingsAssocId") || "");

  useEffect(() => {
    (async () => {
      const { data } = await supabase
        .from("associations")
        .select("id, name")
        .eq("status", "active")
        .order("name");
      const list = (data || []) as AssocOpt[];
      setAssociations(list);
      if (!selectedId && list.length) setSelectedId(list[0].id);
    })();
  }, []);

  useEffect(() => {
    if (selectedId) localStorage.setItem("checkSettingsAssocId", selectedId);
  }, [selectedId]);

  const selected = associations.find((a) => a.id === selectedId);

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Bank Accounts</h1>
        <p className="text-sm text-muted-foreground">Manage bank accounts and configure check printing settings.</p>
      </div>
      <Tabs value={tab} onValueChange={(v) => setParams({ tab: v })}>
        <TabsList>
          <TabsTrigger value="accounts">Bank Accounts</TabsTrigger>
          <TabsTrigger value="check-settings">Check Settings</TabsTrigger>
        </TabsList>
        <TabsContent value="accounts" className="mt-4">
          <BankAccountsPage />
        </TabsContent>
        <TabsContent value="check-settings" className="mt-4 space-y-4">
          <Card className="p-4 flex flex-col sm:flex-row sm:items-center gap-3">
            <Label htmlFor="assoc-select" className="sm:min-w-[140px]">Association</Label>
            <Select value={selectedId} onValueChange={setSelectedId}>
              <SelectTrigger id="assoc-select" className="sm:max-w-md">
                <SelectValue placeholder="Select an association" />
              </SelectTrigger>
              <SelectContent>
                {associations.map((a) => (
                  <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </Card>
          {selected ? (
            <CheckLayoutEditor associationId={selected.id} associationName={selected.name} />
          ) : (
            <Card className="p-12 text-center text-muted-foreground bg-muted/50">
              <Landmark className="h-8 w-8 mx-auto mb-3 text-muted-foreground/50" />
              <p>Select an association above to configure check settings.</p>
            </Card>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}

