"use client";

import { useEffect, useState } from "react";
import { AnimatePresence, motion } from "framer-motion";
import {
  CheckCircle2,
  Moon,
  Store,
  UserCog,
  BellRing,
  Link as LinkIcon,
  AlertCircle,
  Wrench,
  MessageCircle,
} from "lucide-react";
import Link from "next/link";
import { PageHeader } from "@/components/ui/PageHeader";
import { Button } from "@/components/ui/Button";
import { Switch } from "@/components/ui/Switch";
import { ThemeToggle } from "@/components/ui/ThemeToggle";
import { TextField, TextAreaField } from "@/components/ui/Field";
import { Skeleton } from "@/components/ui/Skeleton";
import { useAuth } from "@/lib/auth/auth-provider";
import { createClient } from "@/lib/supabase/client";
import { apiPost, ApiError } from "@/lib/api/client";
import {
  AppSettings,
  DEFAULT_APP_SETTINGS,
  fetchAppSettings,
  saveAppSettings,
} from "@/lib/data/app-settings";

export default function SettingsPage() {
  const { user, profile, refreshProfile } = useAuth();

  const [appSettings, setAppSettings] = useState<AppSettings>(DEFAULT_APP_SETTINGS);
  const [settingsLoading, setSettingsLoading] = useState(true);
  const [admin, setAdmin] = useState({ name: "", email: "", phone: "", currentPassword: "", password: "" });
  const [hydrated, setHydrated] = useState(false);
  const [prefs, setPrefs] = useState({
    emailNewOrder: true,
    emailPaymentPending: true,
    smsAlerts: false,
  });
  const [saved, setSaved] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    fetchAppSettings()
      .then(setAppSettings)
      .catch((err) => setError(err instanceof Error ? err.message : "Couldn't load settings."))
      .finally(() => setSettingsLoading(false));
  }, []);

  useEffect(() => {
    if (hydrated || (!user && !profile)) return;
    setAdmin({
      name: profile?.full_name ?? "",
      phone: profile?.phone ?? "",
      email: user?.email ?? "",
      currentPassword: "",
      password: "",
    });
    setHydrated(true);
  }, [user, profile, hydrated]);

  function updateSetting<K extends keyof AppSettings>(key: K, value: AppSettings[K]) {
    setAppSettings((s) => ({ ...s, [key]: value }));
  }

  async function handleSave() {
    setError(null);

    if (!user) {
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
      return;
    }

    setSaving(true);

    try {
      await apiPost("/api/auth/me", { fullName: admin.name.trim(), phone: admin.phone.trim() }, "PATCH");
    } catch (err) {
      setSaving(false);
      setError(err instanceof ApiError ? err.message : "Couldn't save changes.");
      return;
    }

    // Email change still goes through Supabase — not yet migrated to
    // the MySQL email-change-confirmation flow the User Panel got
    // (see sharednet-ui's requestEmailChange()/confirmEmailChange()).
    // Flagged in the final migration report as a remaining dependency.
    if (admin.email.trim() && admin.email.trim() !== user.email) {
      const supabase = createClient();
      const { error: emailError } = await supabase.auth.updateUser({ email: admin.email.trim() });
      if (emailError) {
        setSaving(false);
        setError(emailError.message);
        return;
      }
    }

    if (admin.password.trim()) {
      if (admin.password.trim().length < 8) {
        setSaving(false);
        setError("New password must be at least 8 characters.");
        return;
      }
      if (!admin.currentPassword.trim()) {
        setSaving(false);
        setError("Enter your current password to set a new one.");
        return;
      }

      // MySQL-backed change-password flow (not Supabase — see
      // lib/db/services/auth.ts's changePassword()). Double-submit
      // CSRF: fetch a token first, then send it back as a header.
      try {
        const csrfResponse = await fetch("/api/csrf");
        const { csrfToken } = await csrfResponse.json();

        const passwordResponse = await fetch("/api/auth/change-password", {
          method: "POST",
          headers: { "Content-Type": "application/json", "x-csrf-token": csrfToken },
          body: JSON.stringify({
            currentPassword: admin.currentPassword.trim(),
            newPassword: admin.password.trim(),
          }),
        });

        if (!passwordResponse.ok) {
          const body = await passwordResponse.json().catch(() => ({}));
          setSaving(false);
          setError(typeof body.error === "string" ? body.error : "Couldn't change your password.");
          return;
        }
      } catch {
        setSaving(false);
        setError("Couldn't change your password. Check your connection and try again.");
        return;
      }
    }

    try {
      await saveAppSettings(appSettings);
    } catch (err) {
      setSaving(false);
      setError(err instanceof Error ? err.message : "Couldn't save app settings.");
      return;
    }

    setSaving(false);

    await refreshProfile();
    setAdmin((a) => ({ ...a, currentPassword: "", password: "" }));
    setSaved(true);
    setTimeout(() => setSaved(false), 2500);
  }

  return (
    <div className="relative">
      <PageHeader title="Settings" subtitle="Manage your business profile, account, and preferences" />

      <div className="grid grid-cols-1 gap-5 xl:grid-cols-2">
        <div className="panel p-5">
          <div className="mb-4 flex items-center gap-2.5">
            <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-gold/12">
              <Store size={16} className="text-gold-dim dark:text-gold-bright" />
            </span>
            <div>
              <h3 className="font-display text-[15px] font-semibold">Business Profile</h3>
              <p className="text-xs text-muted">Shown to customers throughout the app</p>
            </div>
          </div>
          {settingsLoading ? (
            <div className="flex flex-col gap-4">
              <Skeleton className="h-10 w-full" />
              <Skeleton className="h-10 w-full" />
              <Skeleton className="h-10 w-full" />
            </div>
          ) : (
            <div className="flex flex-col gap-4">
              <TextField
                label="Business Name"
                value={appSettings.businessName}
                onChange={(e) => updateSetting("businessName", e.target.value)}
              />
              <TextField
                label="Support Email"
                type="email"
                value={appSettings.supportEmail}
                onChange={(e) => updateSetting("supportEmail", e.target.value)}
              />
              <TextField
                label="Support Phone"
                value={appSettings.supportPhone}
                onChange={(e) => updateSetting("supportPhone", e.target.value)}
              />
            </div>
          )}
        </div>

        <div className="panel p-5">
          <div className="mb-4 flex items-center gap-2.5">
            <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-teal/12">
              <UserCog size={16} className="text-teal-dim dark:text-teal" />
            </span>
            <div>
              <h3 className="font-display text-[15px] font-semibold">Admin Account</h3>
              <p className="text-xs text-muted">Your own login details</p>
            </div>
          </div>
          <div className="flex flex-col gap-4">
            <TextField label="Full Name" value={admin.name} onChange={(e) => setAdmin((a) => ({ ...a, name: e.target.value }))} />
            <TextField label="Email" type="email" value={admin.email} onChange={(e) => setAdmin((a) => ({ ...a, email: e.target.value }))} />
            {admin.email.trim() !== (user?.email ?? "") && admin.email.trim() && (
              <p className="-mt-2 text-xs text-muted">
                Changing your email sends a confirmation link to the new address first.
              </p>
            )}
            <TextField label="Phone" value={admin.phone} onChange={(e) => setAdmin((a) => ({ ...a, phone: e.target.value }))} />
            <TextField
              label="Current Password"
              type="password"
              placeholder="Required only if setting a new password"
              value={admin.currentPassword}
              onChange={(e) => setAdmin((a) => ({ ...a, currentPassword: e.target.value }))}
            />
            <TextField
              label="New Password"
              type="password"
              placeholder="Leave blank to keep current password"
              value={admin.password}
              onChange={(e) => setAdmin((a) => ({ ...a, password: e.target.value }))}
            />
          </div>
        </div>

        <div className="panel p-5 xl:col-span-2">
          <div className="mb-4 flex items-center gap-2.5">
            <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-jazz/15">
              <MessageCircle size={16} className="text-jazz" />
            </span>
            <div>
              <h3 className="font-display text-[15px] font-semibold">App Settings</h3>
              <p className="text-xs text-muted">
                Controls what customers see in the app — updates instantly, no app update needed
              </p>
            </div>
          </div>
          {settingsLoading ? (
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              {Array.from({ length: 6 }).map((_, i) => (
                <Skeleton key={i} className="h-10 w-full" />
              ))}
            </div>
          ) : (
            <div className="flex flex-col gap-4">
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <TextField
                  label="WhatsApp Number"
                  value={appSettings.whatsappNumber}
                  onChange={(e) => updateSetting("whatsappNumber", e.target.value)}
                />
                <TextField
                  label="Support Hours"
                  value={appSettings.supportHours}
                  onChange={(e) => updateSetting("supportHours", e.target.value)}
                />
              </div>
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                <TextField
                  label="Facebook Link"
                  placeholder="https://facebook.com/…"
                  value={appSettings.facebookLink}
                  onChange={(e) => updateSetting("facebookLink", e.target.value)}
                />
                <TextField
                  label="Instagram Link"
                  placeholder="https://instagram.com/…"
                  value={appSettings.instagramLink}
                  onChange={(e) => updateSetting("instagramLink", e.target.value)}
                />
                <TextField
                  label="Telegram Link"
                  placeholder="https://t.me/…"
                  value={appSettings.telegramLink}
                  onChange={(e) => updateSetting("telegramLink", e.target.value)}
                />
              </div>
              <TextAreaField
                label="Payment Instructions (English)"
                rows={2}
                value={appSettings.paymentInstructions.en}
                onChange={(e) =>
                  updateSetting("paymentInstructions", {
                    ...appSettings.paymentInstructions,
                    en: e.target.value,
                  })
                }
              />
              <TextAreaField
                label="Payment Instructions (Urdu — optional)"
                rows={2}
                placeholder="Leave blank to show the English text to Urdu users too"
                value={appSettings.paymentInstructions.ur ?? ""}
                onChange={(e) =>
                  updateSetting("paymentInstructions", {
                    ...appSettings.paymentInstructions,
                    // Empty box is saved as "no translation yet" (null),
                    // not an empty string, so the User Panel's fallback
                    // to English kicks in correctly either way.
                    ur: e.target.value.trim() ? e.target.value : null,
                  })
                }
              />
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <TextField
                  label="App Version"
                  value={appSettings.appVersion}
                  onChange={(e) => updateSetting("appVersion", e.target.value)}
                />
                <div className="flex items-center justify-between rounded-xl border border-danger/20 bg-danger/[0.04] px-4 py-3">
                  <div className="flex items-center gap-2.5">
                    <Wrench size={15} className="text-danger" />
                    <div>
                      <p className="text-sm font-medium">Maintenance Mode</p>
                      <p className="text-[11px] text-muted">Takes the customer app offline instantly</p>
                    </div>
                  </div>
                  <Switch
                    checked={appSettings.maintenanceMode}
                    onChange={(v) => updateSetting("maintenanceMode", v)}
                    label="Maintenance mode"
                  />
                </div>
              </div>
              {appSettings.maintenanceMode && (
                <p className="rounded-xl bg-danger/10 px-3.5 py-2.5 text-xs text-danger">
                  Maintenance mode is ON — customers will see a maintenance screen instead of the app
                  until you turn this off and save.
                </p>
              )}
            </div>
          )}
        </div>

        <div className="panel p-5">
          <div className="mb-4 flex items-center gap-2.5">
            <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-zong/15">
              <Moon size={16} className="text-[#5C8A16] dark:text-[#9FE032]" />
            </span>
            <div>
              <h3 className="font-display text-[15px] font-semibold">Appearance</h3>
              <p className="text-xs text-muted">Switch between light and dark mode</p>
            </div>
          </div>
          <div className="flex items-center justify-between rounded-xl border border-black/[0.06] px-4 py-3.5 dark:border-white/[0.06]">
            <span className="text-sm font-medium">Dark Mode</span>
            <ThemeToggle />
          </div>
        </div>

        <div className="panel p-5">
          <div className="mb-4 flex items-center gap-2.5">
            <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-gold/12">
              <BellRing size={16} className="text-gold-dim dark:text-gold-bright" />
            </span>
            <div>
              <h3 className="font-display text-[15px] font-semibold">Notification Preferences</h3>
              <p className="text-xs text-muted">How you want to be alerted</p>
            </div>
          </div>
          <div className="flex flex-col divide-y divide-black/[0.06] dark:divide-white/[0.06]">
            <div className="flex items-center justify-between py-3">
              <div>
                <p className="text-sm font-medium">Email on new order</p>
                <p className="text-xs text-muted">Get notified the moment an order comes in</p>
              </div>
              <Switch checked={prefs.emailNewOrder} onChange={(v) => setPrefs((p) => ({ ...p, emailNewOrder: v }))} />
            </div>
            <div className="flex items-center justify-between py-3">
              <div>
                <p className="text-sm font-medium">Email on pending payments</p>
                <p className="text-xs text-muted">Daily digest of unverified payments</p>
              </div>
              <Switch checked={prefs.emailPaymentPending} onChange={(v) => setPrefs((p) => ({ ...p, emailPaymentPending: v }))} />
            </div>
            <div className="flex items-center justify-between py-3">
              <div>
                <p className="text-sm font-medium">SMS alerts</p>
                <p className="text-xs text-muted">Text message for urgent items</p>
              </div>
              <Switch checked={prefs.smsAlerts} onChange={(v) => setPrefs((p) => ({ ...p, smsAlerts: v }))} />
            </div>
          </div>
        </div>
      </div>

      <div className="panel mt-5 flex items-center gap-3 p-4">
        <LinkIcon size={16} className="shrink-0 text-muted" />
        <p className="flex-1 text-sm text-muted">
          Looking for JazzCash / EasyPaisa / Bank account details, or website page content?
        </p>
        <div className="flex items-center gap-3">
          <Link href="/payments" className="text-sm font-semibold text-gold-dim dark:text-gold-bright">
            Payments →
          </Link>
          <Link href="/cms" className="text-sm font-semibold text-gold-dim dark:text-gold-bright">
            Website Content →
          </Link>
        </div>
      </div>

      {error && (
        <div className="mt-5 flex items-start gap-2 rounded-xl bg-danger/10 px-3.5 py-3 text-sm text-danger">
          <AlertCircle size={16} className="mt-0.5 shrink-0" />
          {error}
        </div>
      )}

      <div className="mt-6 flex justify-end">
        <Button onClick={handleSave} disabled={saving || settingsLoading}>
          {saving ? "Saving…" : "Save Changes"}
        </Button>
      </div>

      <AnimatePresence>
        {saved && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 20 }}
            className="pointer-events-none fixed bottom-6 left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-2xl bg-success px-4 py-3 text-sm font-semibold text-white shadow-lg"
          >
            <CheckCircle2 size={16} strokeWidth={2.5} />
            Settings saved
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
