import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useRef, useState } from "react";
import { accounting } from "@/lib/accountingClient";
import { supabase } from "@/integrations/supabase/client";
import { useCompanyId } from "./lib/useCompanyId";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Building2, Upload, X, Save, ShieldCheck, ShieldOff, QrCode, Loader2 } from "lucide-react";
import { toast } from "sonner";

const CURRENCIES = ["USD","CAD","EUR","GBP","AUD","MXN","JPY","CHF","NZD"];
const FISCAL_MONTHS = [
  { value: "01-01", label: "January" },
  { value: "02-01", label: "February" },
  { value: "03-01", label: "March" },
  { value: "04-01", label: "April" },
  { value: "05-01", label: "May" },
  { value: "06-01", label: "June" },
  { value: "07-01", label: "July" },
  { value: "08-01", label: "August" },
  { value: "09-01", label: "September" },
  { value: "10-01", label: "October" },
  { value: "11-01", label: "November" },
  { value: "12-01", label: "December" },
];

export default function AccountingGeneralSettingsPage() {
  const { companyId, loading: companyLoading, error: companyError, associationId } = useCompanyId();
  const qc = useQueryClient();
  const cid = companyId ?? "";
  const logoRef = useRef<HTMLInputElement>(null);
  const [saving, setSaving] = useState(false);
  const [uploadingLogo, setUploadingLogo] = useState(false);

  const { data: company, refetch } = useQuery({
    queryKey: ["company-detail", cid],
    enabled: !!cid,
    queryFn: async () =>
      (await accounting.from("companies").select("*").eq("id", cid).single()).data,
  });

  const [form, setForm] = useState<any>(null);
  if (company && !form) {
    setForm({
      name: (company as any).name ?? "",
      address: (company as any).address ?? "",
      phone: (company as any).phone ?? "",
      email: (company as any).email ?? "",
      website: (company as any).website ?? "",
      currency: (company as any).currency ?? "USD",
      fiscal_year_start: (company as any).fiscal_year_start ?? "01-01",
    });
  }

  const f = (patch: any) => setForm((prev: any) => ({ ...prev, ...patch }));

  const save = async () => {
    if (!form?.name?.trim()) return toast.error("Association name is required");
    setSaving(true);
    const { error } = await accounting.from("companies").update({
      name: form.name,
      address: form.address || null,
      phone: form.phone || null,
      email: form.email || null,
      website: form.website || null,
      currency: form.currency,
      fiscal_year_start: form.fiscal_year_start,
    }).eq("id", cid);
    setSaving(false);
    if (error) return toast.error(error.message);
    toast.success("Settings saved");
    qc.invalidateQueries({ queryKey: ["company-detail", cid] });
    refetch();
  };

  const uploadLogo = async (file: File) => {
    setUploadingLogo(true);
    const ext = file.name.split(".").pop() ?? "png";
    const path = `${cid}/logo.${ext}`;
    const { error } = await supabase.storage.from("logos").upload(path, file, {
      contentType: file.type,
      upsert: true,
    });
    if (error) { toast.error(error.message); setUploadingLogo(false); return; }
    const { data } = supabase.storage.from("logos").getPublicUrl(path);
    await accounting.from("companies").update({ logo_url: data.publicUrl + `?t=${Date.now()}` }).eq("id", cid);
    toast.success("Logo uploaded");
    setUploadingLogo(false);
    qc.invalidateQueries({ queryKey: ["company-detail", cid] });
    refetch();
  };

  const removeLogo = async () => {
    await accounting.from("companies").update({ logo_url: null }).eq("id", cid);
    toast.success("Logo removed");
    qc.invalidateQueries({ queryKey: ["company-detail", cid] });
    refetch();
  };

  if (!associationId) return <p className="text-sm text-muted-foreground">Select an association.</p>;
  if (companyLoading) return <div className="flex justify-center py-12"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>;
  if (companyError || !companyId) return <p className="text-sm text-muted-foreground text-center py-12">{companyError || "Accounting setup is not ready."}</p>;
  if (!form) return <div className="text-sm text-muted-foreground">Loading…</div>;

  return (
    <div className="space-y-6 max-w-2xl">

      {/* Association logo */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Association Logo</CardTitle>
          <CardDescription>Displayed on invoices, statements, and check stubs</CardDescription>
        </CardHeader>
        <CardContent className="flex items-center gap-6">
          <div className="h-24 w-24 rounded-lg border-2 border-dashed border-border flex items-center justify-center bg-muted/30 overflow-hidden shrink-0">
            {(company as any)?.logo_url ? (
              <img src={(company as any).logo_url} alt="Logo" className="h-full w-full object-contain p-1" />
            ) : (
              <Building2 className="h-8 w-8 text-muted-foreground" />
            )}
          </div>
          <div className="space-y-2">
            <div className="flex gap-2">
              <Button variant="outline" size="sm" onClick={() => logoRef.current?.click()} disabled={uploadingLogo}>
                <Upload className="h-3.5 w-3.5 mr-1" />
                {uploadingLogo ? "Uploading…" : "Upload logo"}
              </Button>
              {(company as any)?.logo_url && (
                <Button variant="ghost" size="sm" onClick={removeLogo}>
                  <X className="h-3.5 w-3.5 mr-1" /> Remove
                </Button>
              )}
            </div>
            <p className="text-xs text-muted-foreground">PNG, JPG, or SVG · Recommended 200×200px or larger</p>
            <input
              ref={logoRef}
              type="file"
              accept="image/png,image/jpeg,image/svg+xml,image/gif"
              className="hidden"
              onChange={(e) => { const f = e.target.files?.[0]; if (f) uploadLogo(f); e.target.value = ""; }}
            />
          </div>
        </CardContent>
      </Card>

      {/* Association info */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Association Information</CardTitle>
          <CardDescription>Appears on all documents sent to homeowners and vendors</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label>Association name *</Label>
            <Input value={form.name} onChange={(e) => f({ name: e.target.value })} placeholder="Sunrise HOA" />
          </div>
          <div>
            <Label>Mailing / office address</Label>
            <Textarea
              rows={3}
              value={form.address}
              onChange={(e) => f({ address: e.target.value })}
              placeholder={"123 Main Street\nSuite 100\nCity, ST 12345"}
            />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>Phone</Label>
              <Input value={form.phone} onChange={(e) => f({ phone: e.target.value })} placeholder="(555) 000-0000" />
            </div>
            <div>
              <Label>Email</Label>
              <Input type="email" value={form.email} onChange={(e) => f({ email: e.target.value })} placeholder="office@sunrise-hoa.org" />
            </div>
            <div>
              <Label>Website</Label>
              <Input value={form.website} onChange={(e) => f({ website: e.target.value })} placeholder="https://sunrise-hoa.org" />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Financial settings */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Financial Settings</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-2 gap-4">
          <div>
            <Label>Currency</Label>
            <Select value={form.currency} onValueChange={(v) => f({ currency: v })}>
              <SelectTrigger><SelectValue /></SelectTrigger>
              <SelectContent>{CURRENCIES.map((c) => <SelectItem key={c} value={c}>{c}</SelectItem>)}</SelectContent>
            </Select>
          </div>
          <div>
            <Label>Fiscal year start</Label>
            <Select value={form.fiscal_year_start} onValueChange={(v) => f({ fiscal_year_start: v })}>
              <SelectTrigger><SelectValue /></SelectTrigger>
              <SelectContent>
                {FISCAL_MONTHS.map((m) => <SelectItem key={m.value} value={m.value}>{m.label}</SelectItem>)}
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      <MfaSection />

      <div className="flex justify-end">
        <Button onClick={save} disabled={saving}>
          <Save className="h-4 w-4 mr-1" />
          {saving ? "Saving…" : "Save settings"}
        </Button>
      </div>
    </div>
  );
}

function MfaSection() {
  const [factors, setFactors] = useState<any[]>([]);
  const [enrolling, setEnrolling] = useState(false);
  const [qrUri, setQrUri]       = useState<string | null>(null);
  const [secret, setSecret]     = useState<string | null>(null);
  const [factorId, setFactorId] = useState<string | null>(null);
  const [code, setCode]         = useState("");
  const [busy, setBusy]         = useState(false);
  const [loaded, setLoaded]     = useState(false);

  const loadFactors = async () => {
    const { data } = await supabase.auth.mfa.listFactors();
    setFactors(data?.totp ?? []);
    setLoaded(true);
  };

  if (!loaded) { loadFactors(); }

  const startEnroll = async () => {
    setBusy(true);
    const { data, error } = await supabase.auth.mfa.enroll({ factorType: "totp" });
    setBusy(false);
    if (error) { toast.error(error.message); return; }
    setFactorId(data.id);
    setQrUri(data.totp.qr_code);
    setSecret(data.totp.secret);
    setEnrolling(true);
  };

  const confirmEnroll = async () => {
    if (!factorId || code.length < 6) return;
    setBusy(true);
    const { data: challenge, error: cErr } = await supabase.auth.mfa.challenge({ factorId });
    if (cErr) { toast.error(cErr.message); setBusy(false); return; }
    const { error: vErr } = await supabase.auth.mfa.verify({
      factorId, challengeId: challenge.id, code: code.replace(/\s/g, ""),
    });
    setBusy(false);
    if (vErr) { toast.error(vErr.message); return; }
    toast.success("Two-factor authentication enabled");
    setEnrolling(false);
    setQrUri(null); setSecret(null); setFactorId(null); setCode("");
    loadFactors();
  };

  const remove = async (id: string) => {
    if (!confirm("Disable two-factor authentication? Your account will only require a password to sign in.")) return;
    const { error } = await supabase.auth.mfa.unenroll({ factorId: id });
    if (error) { toast.error(error.message); return; }
    toast.success("Two-factor authentication disabled");
    loadFactors();
  };

  const verified = factors.filter(f => f.status === "verified");
  const hasTotp  = verified.length > 0;

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center gap-2">
          <ShieldCheck className="h-4 w-4 text-primary" />
          <CardTitle className="text-base">Two-factor authentication (MFA)</CardTitle>
        </div>
        <CardDescription>
          {hasTotp
            ? "Your account is protected with an authenticator app."
            : "Add an extra layer of security by requiring a code from your phone at sign-in."}
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {hasTotp && !enrolling && (
          <div className="flex items-center justify-between rounded-md border bg-emerald-50 border-emerald-200 px-4 py-3">
            <div className="flex items-center gap-2 text-sm text-emerald-800">
              <ShieldCheck className="h-4 w-4" />
              <span>MFA is <strong>enabled</strong> — authenticator app configured</span>
            </div>
            <Button variant="outline" size="sm" className="text-destructive border-destructive hover:bg-destructive/5"
              onClick={() => remove(verified[0].id)}>
              <ShieldOff className="h-3.5 w-3.5 mr-1" /> Disable
            </Button>
          </div>
        )}

        {!hasTotp && !enrolling && (
          <Button variant="outline" onClick={startEnroll} disabled={busy}>
            <QrCode className="h-4 w-4 mr-1" />
            {busy ? "Setting up…" : "Enable authenticator app"}
          </Button>
        )}

        {enrolling && (
          <div className="space-y-4">
            <div className="rounded-md border bg-muted/30 p-4 space-y-3">
              <p className="text-sm font-medium">Scan this QR code with your authenticator app</p>
              <p className="text-xs text-muted-foreground">Google Authenticator, Authy, 1Password, or any TOTP app.</p>
              {qrUri && (
                <div
                  className="inline-block rounded-md border bg-white p-2"
                  dangerouslySetInnerHTML={{ __html: qrUri }}
                  style={{ maxWidth: 200 }}
                />
              )}
              {secret && (
                <div className="space-y-1">
                  <p className="text-xs text-muted-foreground">Or enter the key manually:</p>
                  <code className="block rounded bg-muted px-3 py-2 text-xs font-mono tracking-widest select-all">
                    {secret}
                  </code>
                </div>
              )}
            </div>

            <div className="space-y-2">
              <Label>Enter the 6-digit code from your app to confirm</Label>
              <div className="flex gap-2">
                <Input
                  type="text"
                  inputMode="numeric"
                  placeholder="000 000"
                  maxLength={7}
                  value={code}
                  onChange={(e) => setCode(e.target.value.replace(/\D/g, "").slice(0, 6))}
                  className="font-mono text-lg tracking-widest text-center max-w-[140px]"
                  autoComplete="one-time-code"
                />
                <Button onClick={confirmEnroll} disabled={busy || code.length < 6}>
                  {busy ? "Verifying…" : "Confirm & enable"}
                </Button>
                <Button variant="ghost" onClick={() => { setEnrolling(false); setQrUri(null); setCode(""); }}>
                  Cancel
                </Button>
              </div>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
