"use client";

import * as React from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { MediaPickerButton } from "@/components/admin/media-picker";
import { toast } from "sonner";
import { Loader2, Save, Building2, Image as ImageIcon, Phone, MapPin, Scale, Share2, Search } from "lucide-react";

export type SettingsValues = {
  id: string;
  companyName: string;
  shortName: string;
  tagline: string;
  logo: string | null;
  favicon: string | null;
  phone: string;
  whatsapp: string;
  email: string;
  address: string;
  mapEmbed: string | null;
  workingHours: string;
  ntn: string;
  footerText: string;
  copyright: string;
  facebook: string | null;
  instagram: string | null;
  linkedin: string | null;
  youtube: string | null;
  twitter: string | null;
  defaultMetaTitle: string;
  defaultMetaDescription: string;
};

function SectionCard({
  icon: Icon,
  title,
  description,
  children,
}: {
  icon: React.ComponentType<{ className?: string }>;
  title: string;
  description?: string;
  children: React.ReactNode;
}) {
  return (
    <Card className="p-6 rounded-2xl space-y-4">
      <div className="flex items-center gap-3">
        <div className="grid place-items-center size-9 rounded-lg bg-[var(--brand-royal)]/10 text-[var(--brand-royal)]">
          <Icon className="size-4.5" />
        </div>
        <div>
          <h2 className="font-bold leading-tight">{title}</h2>
          {description && <p className="text-xs text-muted-foreground">{description}</p>}
        </div>
      </div>
      {children}
    </Card>
  );
}

function Field({
  label,
  children,
  hint,
}: {
  label: string;
  children: React.ReactNode;
  hint?: string;
}) {
  return (
    <div className="space-y-1.5">
      <Label>{label}</Label>
      {children}
      {hint && <p className="text-[11px] text-muted-foreground">{hint}</p>}
    </div>
  );
}

export function SettingsForm({ initial }: { initial: SettingsValues }) {
  const [values, setValues] = React.useState<SettingsValues>(initial);
  const [saving, setSaving] = React.useState(false);

  const set = <K extends keyof SettingsValues>(k: K, v: SettingsValues[K]) =>
    setValues((prev) => ({ ...prev, [k]: v }));

  const onSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      const res = await fetch("/api/admin/settings", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(values),
      });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        throw new Error(d.error || "Failed to save");
      }
      const data = await res.json();
      setValues(data.settings);
      toast.success("Settings saved");
    } catch (err: any) {
      toast.error(err.message || "Something went wrong");
    } finally {
      setSaving(false);
    }
  };

  return (
    <form onSubmit={onSave} className="space-y-6">
      <div className="grid lg:grid-cols-2 gap-6">
        {/* Company Info */}
        <SectionCard icon={Building2} title="Company Info" description="Primary brand identity">
          <Field label="Company Name">
            <Input value={values.companyName} onChange={(e) => set("companyName", e.target.value)} required />
          </Field>
          <Field label="Short Name" hint="Used in compact headers and footers">
            <Input value={values.shortName} onChange={(e) => set("shortName", e.target.value)} />
          </Field>
          <Field label="Tagline">
            <Textarea rows={2} value={values.tagline} onChange={(e) => set("tagline", e.target.value)} />
          </Field>
        </SectionCard>

        {/* Logo & Favicon */}
        <SectionCard icon={ImageIcon} title="Logo & Favicon" description="Brand imagery">
          <Field label="Logo">
            <MediaPickerButton value={values.logo} onChange={(v) => set("logo", v)} accept="image" label="Upload Logo" />
          </Field>
          <Field label="Favicon">
            <MediaPickerButton value={values.favicon} onChange={(v) => set("favicon", v)} accept="image" label="Upload Favicon" />
          </Field>
        </SectionCard>

        {/* Contact Info */}
        <SectionCard icon={Phone} title="Contact Info" description="How customers reach you">
          <div className="grid sm:grid-cols-2 gap-4">
            <Field label="Phone">
              <Input value={values.phone} onChange={(e) => set("phone", e.target.value)} />
            </Field>
            <Field label="WhatsApp" hint="Country code, digits only (e.g. 923012435144)">
              <Input value={values.whatsapp} onChange={(e) => set("whatsapp", e.target.value)} />
            </Field>
          </div>
          <Field label="Email">
            <Input type="email" value={values.email} onChange={(e) => set("email", e.target.value)} />
          </Field>
          <Field label="Address">
            <Textarea rows={2} value={values.address} onChange={(e) => set("address", e.target.value)} />
          </Field>
          <Field label="Working Hours">
            <Input value={values.workingHours} onChange={(e) => set("workingHours", e.target.value)} />
          </Field>
        </SectionCard>

        {/* Map */}
        <SectionCard icon={MapPin} title="Map" description="Google Maps embed">
          <Field label="Map Embed" hint="Paste the iframe HTML or just the src URL from Google Maps embed">
            <Textarea rows={4} value={values.mapEmbed || ""} onChange={(e) => set("mapEmbed", e.target.value)} className="font-mono text-xs" />
          </Field>
        </SectionCard>

        {/* Legal */}
        <SectionCard icon={Scale} title="Legal" description="Tax & footer text">
          <Field label="NTN (Tax ID)">
            <Input value={values.ntn} onChange={(e) => set("ntn", e.target.value)} />
          </Field>
          <Field label="Footer Text">
            <Textarea rows={3} value={values.footerText} onChange={(e) => set("footerText", e.target.value)} />
          </Field>
          <Field label="Copyright Notice">
            <Input value={values.copyright} onChange={(e) => set("copyright", e.target.value)} />
          </Field>
        </SectionCard>

        {/* Social Media */}
        <SectionCard icon={Share2} title="Social Media" description="Optional profile URLs">
          <div className="grid sm:grid-cols-2 gap-4">
            <Field label="Facebook URL">
              <Input value={values.facebook || ""} onChange={(e) => set("facebook", e.target.value || null)} placeholder="https://facebook.com/..." />
            </Field>
            <Field label="Instagram URL">
              <Input value={values.instagram || ""} onChange={(e) => set("instagram", e.target.value || null)} placeholder="https://instagram.com/..." />
            </Field>
            <Field label="LinkedIn URL">
              <Input value={values.linkedin || ""} onChange={(e) => set("linkedin", e.target.value || null)} placeholder="https://linkedin.com/..." />
            </Field>
            <Field label="YouTube URL">
              <Input value={values.youtube || ""} onChange={(e) => set("youtube", e.target.value || null)} placeholder="https://youtube.com/..." />
            </Field>
            <Field label="Twitter / X URL">
              <Input value={values.twitter || ""} onChange={(e) => set("twitter", e.target.value || null)} placeholder="https://x.com/..." />
            </Field>
          </div>
        </SectionCard>

        {/* Default SEO */}
        <SectionCard icon={Search} title="Default SEO" description="Site-wide meta defaults">
          <Field label="Default Meta Title">
            <Input value={values.defaultMetaTitle} onChange={(e) => set("defaultMetaTitle", e.target.value)} />
          </Field>
          <Field label="Default Meta Description">
            <Textarea rows={3} value={values.defaultMetaDescription} onChange={(e) => set("defaultMetaDescription", e.target.value)} />
          </Field>
        </SectionCard>
      </div>

      {/* Sticky save bar */}
      <div className="sticky bottom-4 z-10 flex justify-end">
        <div className="flex items-center gap-2 bg-background/95 backdrop-blur border border-border rounded-xl px-3 py-2 shadow-soft">
          <span className="text-xs text-muted-foreground hidden sm:inline">Last updated {new Date((initial as any).updatedAt || Date.now()).toLocaleString("en-PK")}</span>
          <Button type="submit" disabled={saving} className="brand-gradient text-white">
            {saving ? <Loader2 className="size-4 mr-1.5 animate-spin" /> : <Save className="size-4 mr-1.5" />}
            Save Settings
          </Button>
        </div>
      </div>
    </form>
  );
}
