import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Paintbrush } from "lucide-react";
import LogoUpload from "@/components/LogoUpload";

export default function BrandingSettingsPage() {
  const [companyLogoUrl, setCompanyLogoUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const { toast } = useToast();
  const db = supabase as any;

  useEffect(() => {
    db.from("company_settings").select("value").eq("key", "company_logo_url").maybeSingle().then(({ data }: any) => {
      if (data) setCompanyLogoUrl(data.value);
      setLoading(false);
    });
  }, []);

  const handleLogoChange = async (url: string | null) => {
    setCompanyLogoUrl(url);
    const { error } = await db.from("company_settings").upsert(
      { key: "company_logo_url", value: url, updated_at: new Date().toISOString() },
      { onConflict: "key" }
    );
    if (error) {
      toast({ title: "Error saving logo", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "Company logo updated" });
    }
  };

  return (
    <div className="space-y-6 max-w-2xl">
      <div>
        <h1 className="text-2xl font-bold flex items-center gap-2">
          <Paintbrush className="h-6 w-6 text-primary" />
          Branding
        </h1>
        <p className="text-muted-foreground mt-1">
          Manage your company logo used in PDFs, reports, and letterheads.
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Company Logo</CardTitle>
          <CardDescription>
            This logo appears on all generated PDFs, reports, and email templates as your company branding.
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="h-20 flex items-center text-muted-foreground text-sm">Loading...</div>
          ) : (
            <LogoUpload
              currentUrl={companyLogoUrl}
              storagePath="company"
              onUploaded={handleLogoChange}
              label="Company Logo"
            />
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Association Logos</CardTitle>
          <CardDescription>
            Individual association logos can be uploaded on each association's detail page under the Overview tab.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-muted-foreground">
            Navigate to an association's detail page and use the logo upload section to set association-specific branding for their PDFs and documents.
          </p>
        </CardContent>
      </Card>
    </div>
  );
}
