"use client";

import { useState, useEffect, useRef } from "react";
import { PageHeader } from "@/components/admin/PageHeader";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { toast } from "sonner";
import {
  Save,
  Loader2,
  Building2,
  User,
  Lock,
  Globe2,
  X,
  Eye,
  EyeOff,
  AlertCircle,
} from "lucide-react";
import { uploadToCloudinary } from "@/lib/cloudinary";
import { useImageUpload } from "@/hooks/use-image-upload";
import { ImageDropZone } from "@/components/admin/ImageDropZone";
import {
  getGeneralSettings,
  updateGeneralSettings,
  getSeoSettings,
  updateSeoSettings,
  getAccountSettings,
  updateProfile,
  changePassword,
  type GeneralSettings,
  type SeoSettings,
} from "@/services/settings";

const API_URL = process.env.NEXT_PUBLIC_API_URL || "";

// ── General / Company Info tab ────────────────────────────────────────────────

function GeneralTabContent() {
  const [form, setForm] = useState<GeneralSettings>({
    company_name: "",
    tagline: "",
    address: "",
    phone_primary: "",
    phone_secondary: "",
    email_general: "",
    email_support: "",
    social_linkedin: "",
    social_facebook: "",
    social_twitter: "",
    social_youtube: "",
    social_instagram: "",
    logo_light_url: "",
    logo_light_public_id: "",
    logo_dark_url: "",
    logo_dark_public_id: "",
    favicon_url: "",
    favicon_public_id: "",
    footer_image_url: "",
    footer_image_public_id: "",
  });
  const [loading, setLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const fetchedRef = useRef(false);

  // Image upload hooks (separate instances for each image)
  const lightLogo = useImageUpload();
  const darkLogo = useImageUpload();
  const faviconUpload = useImageUpload();
  const footerImage = useImageUpload();

  const [lightProgress, setLightProgress] = useState(0);
  const [darkProgress, setDarkProgress] = useState(0);
  const [faviconProgress, setFaviconProgress] = useState(0);
  const [footerProgress, setFooterProgress] = useState(0);

  const [isUploadingLight, setIsUploadingLight] = useState(false);
  const [isUploadingDark, setIsUploadingDark] = useState(false);
  const [isUploadingFavicon, setIsUploadingFavicon] = useState(false);
  const [isUploadingFooter, setIsUploadingFooter] = useState(false);

  useEffect(() => {
    if (fetchedRef.current) return;
    fetchedRef.current = true;
    getGeneralSettings()
      .then((data) => setForm({
        company_name: data.company_name ?? "",
        tagline: data.tagline ?? "",
        address: data.address ?? "",
        phone_primary: data.phone_primary ?? "",
        phone_secondary: data.phone_secondary ?? "",
        email_general: data.email_general ?? "",
        email_support: data.email_support ?? "",
        social_linkedin: data.social_linkedin ?? "",
        social_facebook: data.social_facebook ?? "",
        social_twitter: data.social_twitter ?? "",
        social_youtube: data.social_youtube ?? "",
        social_instagram: data.social_instagram ?? "",
        logo_light_url: data.logo_light_url ?? "",
        logo_light_public_id: data.logo_light_public_id ?? "",
        logo_dark_url: data.logo_dark_url ?? "",
        logo_dark_public_id: data.logo_dark_public_id ?? "",
        favicon_url: data.favicon_url ?? "",
        favicon_public_id: data.favicon_public_id ?? "",
        footer_image_url: data.footer_image_url ?? "",
        footer_image_public_id: data.footer_image_public_id ?? "",
      }))
      .finally(() => setLoading(false));
  }, []);

  const set = (key: keyof GeneralSettings) => (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => setForm((prev) => ({ ...prev, [key]: e.target.value }));

  const handleSave = async () => {
    if (!form.company_name.trim()) {
      toast.error("Company name is required.");
      return;
    }
    setIsSaving(true);
    try {
      let finalForm = { ...form } as GeneralSettings;

      // Upload light logo
      if (lightLogo.file) {
        setIsUploadingLight(true);
        setLightProgress(0);
        try {
          const res = await uploadToCloudinary(
            lightLogo.file,
            "image",
            setLightProgress,
            `${API_URL}/api/settings/general/logo-light/upload-signature`,
          );
          finalForm.logo_light_url = res.secure_url;
          finalForm.logo_light_public_id = res.public_id;
          lightLogo.reset();
        } finally {
          setIsUploadingLight(false);
        }
      }

      // Upload dark logo
      if (darkLogo.file) {
        setIsUploadingDark(true);
        setDarkProgress(0);
        try {
          const res = await uploadToCloudinary(
            darkLogo.file,
            "image",
            setDarkProgress,
            `${API_URL}/api/settings/general/logo-dark/upload-signature`,
          );
          finalForm.logo_dark_url = res.secure_url;
          finalForm.logo_dark_public_id = res.public_id;
          darkLogo.reset();
        } finally {
          setIsUploadingDark(false);
        }
      }

      // Upload favicon
      if (faviconUpload.file) {
        setIsUploadingFavicon(true);
        setFaviconProgress(0);
        try {
          const res = await uploadToCloudinary(
            faviconUpload.file,
            "image",
            setFaviconProgress,
            `${API_URL}/api/settings/general/favicon/upload-signature`,
          );
          finalForm.favicon_url = res.secure_url;
          finalForm.favicon_public_id = res.public_id;
          faviconUpload.reset();
        } finally {
          setIsUploadingFavicon(false);
        }
      }

      // Upload footer image
      if (footerImage.file) {
        setIsUploadingFooter(true);
        setFooterProgress(0);
        try {
          const res = await uploadToCloudinary(
            footerImage.file,
            "image",
            setFooterProgress,
            `${API_URL}/api/settings/general/footer-image/upload-signature`,
          );
          finalForm.footer_image_url = res.secure_url;
          finalForm.footer_image_public_id = res.public_id;
          footerImage.reset();
        } finally {
          setIsUploadingFooter(false);
        }
      }

      await updateGeneralSettings(finalForm);
      setForm(finalForm);
      toast.success("General settings saved.");
    } catch (e) {
      // interceptor shows toast
    } finally {
      setIsSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="max-w-2xl space-y-4">
        {Array.from({ length: 8 }).map((_, i) => (
          <Skeleton key={i} className="h-10 w-full" />
        ))}
      </div>
    );
  }

  return (
    <div className="max-w-2xl space-y-8">
      {/* Company */}
      <div className="space-y-4">
        <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
          <Building2 className="h-4 w-4 text-muted-foreground" />
          Company
        </h3>
        <div className="grid grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label htmlFor="company_name">Company Name *</Label>
            <Input
              id="company_name"
              value={form.company_name}
              onChange={set("company_name")}
              placeholder="Petro-Base Group"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="tagline">Tagline</Label>
            <Input
              id="tagline"
              value={form.tagline}
              onChange={set("tagline")}
              placeholder="Your global inspection partner"
            />
          </div>
        </div>
        <div className="space-y-2">
          <Label htmlFor="address">Physical Address</Label>
          <Textarea
            id="address"
            value={form.address}
            onChange={set("address")}
            rows={2}
            placeholder="123 Industrial Ave, Port Harcourt, Nigeria"
          />
        </div>
      </div>

      <Separator />

      {/* Contact */}
      <div className="space-y-4">
        <h3 className="text-sm font-semibold text-foreground">Contact</h3>
        <div className="grid grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label htmlFor="phone_primary">Primary Phone</Label>
            <Input
              id="phone_primary"
              type="tel"
              value={form.phone_primary}
              onChange={set("phone_primary")}
              placeholder="+234 800 000 0000"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="phone_secondary">Secondary Phone</Label>
            <Input
              id="phone_secondary"
              type="tel"
              value={form.phone_secondary}
              onChange={set("phone_secondary")}
              placeholder="+234 800 000 0001"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="email_general">General Email</Label>
            <Input
              id="email_general"
              type="email"
              value={form.email_general}
              onChange={set("email_general")}
              placeholder="info@petrobasegroup.com"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="email_support">Support Email</Label>
            <Input
              id="email_support"
              type="email"
              value={form.email_support}
              onChange={set("email_support")}
              placeholder="support@petrobasegroup.com"
            />
          </div>
        </div>
      </div>

      <Separator />

      {/* Social */}
      <div className="space-y-4">
        <h3 className="text-sm font-semibold text-foreground">Social Media</h3>
        <div className="grid grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label htmlFor="social_linkedin">LinkedIn</Label>
            <Input
              id="social_linkedin"
              value={form.social_linkedin}
              onChange={set("social_linkedin")}
              placeholder="https://linkedin.com/company/..."
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="social_facebook">Facebook</Label>
            <Input
              id="social_facebook"
              value={form.social_facebook}
              onChange={set("social_facebook")}
              placeholder="https://facebook.com/..."
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="social_twitter">X / Twitter</Label>
            <Input
              id="social_twitter"
              value={form.social_twitter}
              onChange={set("social_twitter")}
              placeholder="https://x.com/..."
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="social_youtube">YouTube</Label>
            <Input
              id="social_youtube"
              value={form.social_youtube}
              onChange={set("social_youtube")}
              placeholder="https://youtube.com/@..."
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="social_instagram">Instagram</Label>
            <Input
              id="social_instagram"
              value={form.social_instagram}
              onChange={set("social_instagram")}
              placeholder="https://instagram.com/..."
            />
          </div>
        </div>
      </div>

      <Separator />

      {/* Branding */}
      <div className="space-y-4">
        <h3 className="text-sm font-semibold text-foreground">Branding</h3>
        <p className="text-sm text-muted-foreground">Upload site logos, favicon, and footer image.</p>
        <div className="grid grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label>Logo — Light</Label>
            <ImageDropZone
              preview={lightLogo.preview}
              fallback={form.logo_light_url || undefined}
              isDragging={lightLogo.isDragging}
              onDragOver={(e) => { e.preventDefault(); lightLogo.setIsDragging(true); }}
              onDragLeave={() => lightLogo.setIsDragging(false)}
              onDrop={lightLogo.onDrop}
              onClick={() => lightLogo.inputRef.current?.click()}
            />
            <input
              ref={lightLogo.inputRef}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={(e) => { const f = e.target.files?.[0]; if (f) lightLogo.handleFile(f); }}
            />
            {lightLogo.preview && (
              <button type="button" onClick={lightLogo.reset} className="text-xs text-muted-foreground hover:underline flex items-center gap-1">
                <X className="h-3 w-3" /> Cancel new selection
              </button>
            )}
            {!lightLogo.preview && form.logo_light_url && (
              <button type="button" onClick={() => setForm((p) => ({ ...p, logo_light_url: "", logo_light_public_id: "" }))} className="text-xs text-destructive hover:underline flex items-center gap-1">
                <X className="h-3 w-3" /> Remove image
              </button>
            )}
            {isUploadingLight && (
              <div className="space-y-1">
                <div className="h-1.5 w-full rounded-full bg-muted overflow-hidden">
                  <div className="h-full bg-primary" style={{ width: `${lightProgress}%` }} />
                </div>
                <p className="text-xs text-muted-foreground">Uploading… {lightProgress}%</p>
              </div>
            )}
          </div>

          <div className="space-y-2">
            <Label>Logo — Dark</Label>
            <ImageDropZone
              preview={darkLogo.preview}
              fallback={form.logo_dark_url || undefined}
              isDragging={darkLogo.isDragging}
              onDragOver={(e) => { e.preventDefault(); darkLogo.setIsDragging(true); }}
              onDragLeave={() => darkLogo.setIsDragging(false)}
              onDrop={darkLogo.onDrop}
              onClick={() => darkLogo.inputRef.current?.click()}
            />
            <input
              ref={darkLogo.inputRef}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={(e) => { const f = e.target.files?.[0]; if (f) darkLogo.handleFile(f); }}
            />
            {darkLogo.preview && (
              <button type="button" onClick={darkLogo.reset} className="text-xs text-muted-foreground hover:underline flex items-center gap-1">
                <X className="h-3 w-3" /> Cancel new selection
              </button>
            )}
            {!darkLogo.preview && form.logo_dark_url && (
              <button type="button" onClick={() => setForm((p) => ({ ...p, logo_dark_url: "", logo_dark_public_id: "" }))} className="text-xs text-destructive hover:underline flex items-center gap-1">
                <X className="h-3 w-3" /> Remove image
              </button>
            )}
            {isUploadingDark && (
              <div className="space-y-1">
                <div className="h-1.5 w-full rounded-full bg-muted overflow-hidden">
                  <div className="h-full bg-primary" style={{ width: `${darkProgress}%` }} />
                </div>
                <p className="text-xs text-muted-foreground">Uploading… {darkProgress}%</p>
              </div>
            )}
          </div>

          <div className="space-y-2">
            <Label>Favicon</Label>
            <ImageDropZone
              preview={faviconUpload.preview}
              fallback={form.favicon_url || undefined}
              isDragging={faviconUpload.isDragging}
              onDragOver={(e) => { e.preventDefault(); faviconUpload.setIsDragging(true); }}
              onDragLeave={() => faviconUpload.setIsDragging(false)}
              onDrop={faviconUpload.onDrop}
              onClick={() => faviconUpload.inputRef.current?.click()}
            />
            <input
              ref={faviconUpload.inputRef}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={(e) => { const f = e.target.files?.[0]; if (f) faviconUpload.handleFile(f); }}
            />
            {faviconUpload.preview && (
              <button type="button" onClick={faviconUpload.reset} className="text-xs text-muted-foreground hover:underline flex items-center gap-1">
                <X className="h-3 w-3" /> Cancel new selection
              </button>
            )}
            {!faviconUpload.preview && form.favicon_url && (
              <button type="button" onClick={() => setForm((p) => ({ ...p, favicon_url: "", favicon_public_id: "" }))} className="text-xs text-destructive hover:underline flex items-center gap-1">
                <X className="h-3 w-3" /> Remove image
              </button>
            )}
            {isUploadingFavicon && (
              <div className="space-y-1">
                <div className="h-1.5 w-full rounded-full bg-muted overflow-hidden">
                  <div className="h-full bg-primary" style={{ width: `${faviconProgress}%` }} />
                </div>
                <p className="text-xs text-muted-foreground">Uploading… {faviconProgress}%</p>
              </div>
            )}
          </div>

          <div className="col-span-2 space-y-2">
            <Label>Footer Image</Label>
            <ImageDropZone
              preview={footerImage.preview}
              fallback={form.footer_image_url || undefined}
              isDragging={footerImage.isDragging}
              onDragOver={(e) => { e.preventDefault(); footerImage.setIsDragging(true); }}
              onDragLeave={() => footerImage.setIsDragging(false)}
              onDrop={footerImage.onDrop}
              onClick={() => footerImage.inputRef.current?.click()}
            />
            <input
              ref={footerImage.inputRef}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={(e) => { const f = e.target.files?.[0]; if (f) footerImage.handleFile(f); }}
            />
            {footerImage.preview && (
              <button type="button" onClick={footerImage.reset} className="text-xs text-muted-foreground hover:underline flex items-center gap-1">
                <X className="h-3 w-3" /> Cancel new selection
              </button>
            )}
            {!footerImage.preview && form.footer_image_url && (
              <button type="button" onClick={() => setForm((p) => ({ ...p, footer_image_url: "", footer_image_public_id: "" }))} className="text-xs text-destructive hover:underline flex items-center gap-1">
                <X className="h-3 w-3" /> Remove image
              </button>
            )}
            {isUploadingFooter && (
              <div className="space-y-1">
                <div className="h-1.5 w-full rounded-full bg-muted overflow-hidden">
                  <div className="h-full bg-primary" style={{ width: `${footerProgress}%` }} />
                </div>
                <p className="text-xs text-muted-foreground">Uploading… {footerProgress}%</p>
              </div>
            )}
          </div>
        </div>
      </div>

      <Button onClick={handleSave} disabled={isSaving} className="gap-2">
        {isSaving ? (
          <Loader2 className="h-4 w-4 animate-spin" />
        ) : (
          <Save className="h-4 w-4" />
        )}
        Save Changes
      </Button>
    </div>
  );
}


// ── Account & Security tab ────────────────────────────────────────────────────

function AccountTabContent() {
  // Profile section
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [isSavingProfile, setIsSavingProfile] = useState(false);
  const [loadingAccount, setLoadingAccount] = useState(true);

  // Password section
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [isSavingPassword, setIsSavingPassword] = useState(false);
  const [passwordError, setPasswordError] = useState("");

  // Show/hide toggles
  const [showCurrent, setShowCurrent] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);

  const fetchedRef = useRef(false);

  useEffect(() => {
    if (fetchedRef.current) return;
    fetchedRef.current = true;
    getAccountSettings()
      .then((data) => {
        setName(data.name ?? "");
        setEmail(data.email ?? "");
      })
      .finally(() => setLoadingAccount(false));
  }, []);

  const handleSaveProfile = async () => {
    if (!name.trim()) { toast.error("Name is required."); return; }
    if (!email.trim()) { toast.error("Email is required."); return; }
    setIsSavingProfile(true);
    try {
      const updated = await updateProfile({ name: name.trim(), email: email.trim() });
      setName(updated.name);
      setEmail(updated.email);
      // Keep localStorage in sync for the sidebar display
      try {
        const raw = localStorage.getItem("user");
        if (raw) {
          localStorage.setItem(
            "user",
            JSON.stringify({ ...JSON.parse(raw), name: updated.name, email: updated.email }),
          );
        }
      } catch {}
      toast.success("Profile updated.");
    } catch {
      // interceptor shows toast
    } finally {
      setIsSavingProfile(false);
    }
  };

  const handleChangePassword = async () => {
    setPasswordError("");
    if (!currentPassword) { setPasswordError("Current password is required."); return; }
    if (!newPassword) { toast.error("New password is required."); return; }
    if (newPassword.length < 8) { toast.error("New password must be at least 8 characters."); return; }
    if (newPassword !== confirmPassword) { toast.error("Passwords do not match."); return; }
    setIsSavingPassword(true);
    try {
      await changePassword({
        current_password: currentPassword,
        password: newPassword,
        password_confirmation: confirmPassword,
      });
      toast.success("Password changed successfully.");
      setCurrentPassword("");
      setNewPassword("");
      setConfirmPassword("");
      setShowCurrent(false);
      setShowNew(false);
      setShowConfirm(false);
    } catch (err: any) {
      const msg =
        err?.response?.data?.message ||
        err?.response?.data?.error ||
        err?.message ||
        "Failed to change password.";
      setPasswordError(msg);
    } finally {
      setIsSavingPassword(false);
    }
  };

  if (loadingAccount) {
    return (
      <div className="max-w-lg space-y-4">
        <Skeleton className="h-10 w-full" />
        <Skeleton className="h-10 w-full" />
      </div>
    );
  }

  return (
    <div className="max-w-lg space-y-10">
      {/* Profile */}
      <div className="space-y-4">
        <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
          <User className="h-4 w-4 text-muted-foreground" />
          Profile
        </h3>
        <p className="text-sm text-muted-foreground">
          Update the display name and email address for your admin account.
        </p>
        <div className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="profile_name">Full Name</Label>
            <Input
              id="profile_name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Admin User"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="profile_email">Email Address</Label>
            <Input
              id="profile_email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="admin@petrobasegroup.com"
            />
          </div>
        </div>
        <Button onClick={handleSaveProfile} disabled={isSavingProfile} className="gap-2">
          {isSavingProfile ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : (
            <Save className="h-4 w-4" />
          )}
          Save Profile
        </Button>
      </div>

      <Separator />

      {/* Password */}
      <div className="space-y-4">
        <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
          <Lock className="h-4 w-4 text-muted-foreground" />
          Change Password
        </h3>
        <p className="text-sm text-muted-foreground">
          Choose a strong password of at least 8 characters.
        </p>
        <div className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="current_password">Current Password</Label>
            {passwordError && (
              <div className="flex items-center gap-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive">
                <AlertCircle className="h-3.5 w-3.5 shrink-0" />
                {passwordError}
              </div>
            )}
            <div className="relative">
              <Input
                id="current_password"
                type={showCurrent ? "text" : "password"}
                value={currentPassword}
                onChange={(e) => { setCurrentPassword(e.target.value); setPasswordError(""); }}
                autoComplete="current-password"
                className="pr-10"
              />
              <button
                type="button"
                onClick={() => setShowCurrent((v) => !v)}
                className="absolute inset-y-0 right-0 flex items-center px-3 text-muted-foreground hover:text-foreground"
                tabIndex={-1}
              >
                {showCurrent ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
          </div>
          <div className="space-y-2">
            <Label htmlFor="new_password">New Password</Label>
            <div className="relative">
              <Input
                id="new_password"
                type={showNew ? "text" : "password"}
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                autoComplete="new-password"
                className="pr-10"
              />
              <button
                type="button"
                onClick={() => setShowNew((v) => !v)}
                className="absolute inset-y-0 right-0 flex items-center px-3 text-muted-foreground hover:text-foreground"
                tabIndex={-1}
              >
                {showNew ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
          </div>
          <div className="space-y-2">
            <Label htmlFor="confirm_password">Confirm New Password</Label>
            <div className="relative">
              <Input
                id="confirm_password"
                type={showConfirm ? "text" : "password"}
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                autoComplete="new-password"
                className="pr-10"
              />
              <button
                type="button"
                onClick={() => setShowConfirm((v) => !v)}
                className="absolute inset-y-0 right-0 flex items-center px-3 text-muted-foreground hover:text-foreground"
                tabIndex={-1}
              >
                {showConfirm ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
          </div>
        </div>
        <Button onClick={handleChangePassword} disabled={isSavingPassword} className="gap-2">
          {isSavingPassword ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : (
            <Lock className="h-4 w-4" />
          )}
          Change Password
        </Button>
      </div>
    </div>
  );
}

// ── SEO Defaults tab ──────────────────────────────────────────────────────────

function SeoTabContent() {
  const [form, setForm] = useState<SeoSettings>({
    meta_title_suffix: "",
    meta_description: "",
    og_image_url: "",
    og_image_public_id: "",
    google_analytics_id: "",
    google_tag_manager_id: "",
    robots_noindex: false,
  });
  const [loading, setLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [imageProgress, setImageProgress] = useState(0);
  const [isUploading, setIsUploading] = useState(false);
  const fetchedRef = useRef(false);
  const { preview, file, isDragging, setIsDragging, inputRef, handleFile, onDrop, reset: resetImage } = useImageUpload();

  useEffect(() => {
    if (fetchedRef.current) return;
    fetchedRef.current = true;
    getSeoSettings()
      .then((data) => setForm({
        meta_title_suffix: data.meta_title_suffix ?? "",
        meta_description: data.meta_description ?? "",
        og_image_url: data.og_image_url ?? "",
        og_image_public_id: data.og_image_public_id ?? "",
        google_analytics_id: data.google_analytics_id ?? "",
        google_tag_manager_id: data.google_tag_manager_id ?? "",
        robots_noindex: data.robots_noindex ?? false,
      }))
      .finally(() => setLoading(false));
  }, []);

  const set =
    (key: keyof SeoSettings) =>
    (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
      setForm((prev) => ({ ...prev, [key]: e.target.value }));

  const handleSave = async () => {
    setIsSaving(true);
    try {
      let finalForm = form;
      if (file) {
        setIsUploading(true);
        setImageProgress(0);
        try {
          const result = await uploadToCloudinary(
            file,
            "image",
            setImageProgress,
            `${API_URL}/api/settings/seo/og-image/upload-signature`,
          );
          finalForm = {
            ...form,
            og_image_url: result.secure_url,
            og_image_public_id: result.public_id,
          };
          setForm(finalForm);
          resetImage();
        } finally {
          setIsUploading(false);
        }
      }
      await updateSeoSettings(finalForm);
      toast.success("SEO defaults saved.");
    } catch {
      // interceptor shows toast
    } finally {
      setIsSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="max-w-2xl space-y-4">
        {Array.from({ length: 6 }).map((_, i) => (
          <Skeleton key={i} className="h-10 w-full" />
        ))}
      </div>
    );
  }

  return (
    <div className="max-w-2xl space-y-8">
      {/* Meta */}
      <div className="space-y-4">
        <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
          <Globe2 className="h-4 w-4 text-muted-foreground" />
          Meta Tags
        </h3>
        <p className="text-sm text-muted-foreground">
          These are fallback values used when a specific page has no SEO data set.
        </p>
        <div className="space-y-2">
          <Label htmlFor="meta_title_suffix">Title Suffix</Label>
          <Input
            id="meta_title_suffix"
            value={form.meta_title_suffix}
            onChange={set("meta_title_suffix")}
            placeholder="| Petrobase Group"
          />
          <p className="text-xs text-muted-foreground">
            Appended to every page title — e.g. &ldquo;Services{" "}
            {form.meta_title_suffix || "| Petrobase Group"}&rdquo;
          </p>
        </div>
        <div className="space-y-2">
          <Label htmlFor="meta_description">Default Meta Description</Label>
          <Textarea
            id="meta_description"
            value={form.meta_description}
            onChange={set("meta_description")}
            rows={3}
            placeholder="Petrobase Group provides world-class inspection and engineering services..."
          />
          <p className="text-xs text-muted-foreground">
            {form.meta_description.length} / 160 characters recommended
          </p>
        </div>
      </div>

      <Separator />

      {/* Open Graph */}
      <div className="space-y-4">
        <h3 className="text-sm font-semibold text-foreground">Open Graph Image</h3>
        <p className="text-sm text-muted-foreground">
          Default image shown when pages are shared on social media (1200 × 630 px recommended).
        </p>
        <ImageDropZone
          preview={preview}
          fallback={form.og_image_url || undefined}
          isDragging={isDragging}
          onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
          onDragLeave={() => setIsDragging(false)}
          onDrop={onDrop}
          onClick={() => inputRef.current?.click()}
        />
        <input
          ref={inputRef}
          type="file"
          accept="image/*"
          className="hidden"
          onChange={(e) => { const f = e.target.files?.[0]; if (f) handleFile(f); }}
        />
        {(preview || form.og_image_url) && !preview && (
          <button
            type="button"
            onClick={() => setForm((prev) => ({ ...prev, og_image_url: "", og_image_public_id: "" }))}
            className="flex items-center gap-1 text-xs text-destructive hover:underline"
          >
            <X className="h-3 w-3" /> Remove image
          </button>
        )}
        {preview && (
          <button
            type="button"
            onClick={resetImage}
            className="flex items-center gap-1 text-xs text-muted-foreground hover:underline"
          >
            <X className="h-3 w-3" /> Cancel new selection
          </button>
        )}
        {isUploading && (
          <div className="space-y-1">
            <div className="h-1.5 w-full rounded-full bg-muted overflow-hidden">
              <div
                className="h-full bg-primary transition-all duration-200"
                style={{ width: `${imageProgress}%` }}
              />
            </div>
            <p className="text-xs text-muted-foreground">Uploading… {imageProgress}%</p>
          </div>
        )}
      </div>

      <Separator />

      {/* Analytics */}
      <div className="space-y-4">
        <h3 className="text-sm font-semibold text-foreground">Analytics</h3>
        <div className="grid grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label htmlFor="google_analytics_id">Google Analytics ID</Label>
            <Input
              id="google_analytics_id"
              value={form.google_analytics_id}
              onChange={set("google_analytics_id")}
              placeholder="G-XXXXXXXXXX"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="google_tag_manager_id">Google Tag Manager ID</Label>
            <Input
              id="google_tag_manager_id"
              value={form.google_tag_manager_id}
              onChange={set("google_tag_manager_id")}
              placeholder="GTM-XXXXXXX"
            />
          </div>
        </div>
      </div>

      <Separator />

      {/* Robots */}
      <div className="space-y-4">
        <h3 className="text-sm font-semibold text-foreground">Crawling</h3>
        <div className="flex items-center justify-between rounded-lg border p-4">
          <div className="space-y-0.5">
            <Label htmlFor="robots_noindex" className="text-sm font-medium cursor-pointer">
              Block all search engines (noindex)
            </Label>
            <p className="text-xs text-muted-foreground">
              Adds a global{" "}
              <code className="bg-muted px-1 rounded text-[11px]">noindex, nofollow</code> robots
              tag to every page. Use during development or maintenance.
            </p>
          </div>
          <Switch
            id="robots_noindex"
            checked={form.robots_noindex}
            onCheckedChange={(checked) =>
              setForm((prev) => ({ ...prev, robots_noindex: checked }))
            }
          />
        </div>
      </div>

      <Button onClick={handleSave} disabled={isSaving} className="gap-2">
        {isSaving ? (
          <Loader2 className="h-4 w-4 animate-spin" />
        ) : (
          <Save className="h-4 w-4" />
        )}
        Save Changes
      </Button>
    </div>
  );
}

// ── Page ──────────────────────────────────────────────────────────────────────

export default function SettingsPage() {
  return (
    <div className="p-6 lg:p-8 max-w-7xl mx-auto">
      <PageHeader
        title="System Settings"
        description="Manage site-wide configuration and your admin account."
      />

      <Tabs defaultValue="general">
        <TabsList className="mb-8">
          <TabsTrigger value="general">General</TabsTrigger>
          <TabsTrigger value="account">Account &amp; Security</TabsTrigger>
          <TabsTrigger value="seo">SEO Defaults</TabsTrigger>
        </TabsList>

        <TabsContent value="general">
          <GeneralTabContent />
        </TabsContent>

        <TabsContent value="account">
          <AccountTabContent />
        </TabsContent>

        <TabsContent value="seo">
          <SeoTabContent />
        </TabsContent>
      </Tabs>
    </div>
  );
}
