import { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Loader2, Save, Building2 } from "lucide-react";
import CompanyBankAccountsPage from "@/pages/CompanyBankAccountsPage";
import CheckLayoutEditor from "@/components/CheckLayoutEditor";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";

const COMPANY_ID = "__company__";

export default function CompanyBankAccountsHubPage() {
  const [params, setParams] = useSearchParams();
  const tab = (() => {
    const t = params.get("tab");
    return t === "check-settings" || t === "company-info" ? t : "accounts";
  })();
  const { toast } = useToast();

  const [loadingSettings, setLoadingSettings] = useState(true);
  const [savingSettings, setSavingSettings] = useState(false);
  const [settingsId, setSettingsId] = useState<string | null>(null);
  const [companyName, setCompanyName] = useState("");

  useEffect(() => {
    let cancelled = false;
    (async () => {
      setLoadingSettings(true);
      const { data } = await supabase
        .from("company_settings")
        .select("*")
        .eq("key", "primary")
        .maybeSingle();
      if (cancelled) return;
      if (data) {
        setSettingsId(data.id);
        setCompanyName(data.company_name || "");
      }
      setLoadingSettings(false);
    })();
    return () => { cancelled = true; };
  }, []);

  const handleSaveSettings = async () => {
    setSavingSettings(true);
    try {
      const payload = {
        key: "primary",
        company_name: companyName.trim() || null,
      };
      if (settingsId) {
        const { error } = await supabase.from("company_settings").update(payload).eq("id", settingsId);
        if (error) throw error;
      } else {
        const { data, error } = await supabase
          .from("company_settings")
          .insert(payload)
          .select("id")
          .single();
        if (error) throw error;
        setSettingsId(data.id);
      }
      toast({ title: "Company settings saved" });
    } catch (err: any) {
      toast({ variant: "destructive", title: "Save failed", description: err.message });
    } finally {
      setSavingSettings(false);
    }
  };

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Company Bank Accounts</h1>
        <p className="text-sm text-muted-foreground">
          Manage your management company's own bank accounts and check printing layout — kept separate from client associations.
        </p>
      </div>
      <Tabs value={tab} onValueChange={(v) => setParams({ tab: v })}>
        <TabsList>
          <TabsTrigger value="accounts">Bank Accounts</TabsTrigger>
          <TabsTrigger value="check-settings">Check Settings</TabsTrigger>
          <TabsTrigger value="company-info">Company Info</TabsTrigger>
        </TabsList>

        <TabsContent value="accounts" className="mt-4">
          <CompanyBankAccountsPage />
        </TabsContent>

        <TabsContent value="check-settings" className="mt-4">
          <CheckLayoutEditor
            mode="company"
            associationId={COMPANY_ID}
            associationName={companyName || "Management Company"}
          />
        </TabsContent>

        <TabsContent value="company-info" className="mt-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-base">
                <Building2 className="h-4 w-4 text-primary" /> Management Company Info
              </CardTitle>
              <CardDescription>
                Your management company's profile information.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {loadingSettings ? (
                <div className="flex justify-center py-8">
                  <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
                </div>
              ) : (
                <>
                  <div className="grid gap-2 sm:max-w-md">
                    <Label htmlFor="company-name">Company Name</Label>
                    <Input
                      id="company-name"
                      value={companyName}
                      onChange={(e) => setCompanyName(e.target.value)}
                      placeholder="Avria Community Management"
                    />
                  </div>
                  <div className="pt-2">
                    <Button onClick={handleSaveSettings} disabled={savingSettings} className="gap-2">
                      {savingSettings ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
                      {savingSettings ? "Saving…" : "Save Company Info"}
                    </Button>
                  </div>
                </>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
