"use client";
// src/app/settings/page.tsx
import { useState, useMemo, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { AppShell } from "@/components/layout/AppShell";
import { Input, Button, Card, CardHeader, CardTitle, CardContent } from "@/components/ui/index";
import { useAuth } from "@/hooks/useAuth";
import { useLanguage } from "@/i18n/LanguageContext";
import { toast } from "sonner";
import { getInitials } from "@/lib/utils";
import { Globe, Lock, User, Bell, Mail, ListOrdered } from "lucide-react";
import { CustomFieldsSettingsPanel } from "@/components/custom-fields/CustomFieldsSettingsPanel";
import { createProfileSettingsSchema, createPasswordChangeSchema } from "@/lib/validations";
import { ROLE_LABEL_KEYS } from "@/lib/roleLabels";
import type { TranslationKey } from "@/i18n/translations";
import { hasPermission } from "@/lib/permissions";

type ProfileInput = z.infer<ReturnType<typeof createProfileSettingsSchema>>;
type PasswordInput = z.infer<ReturnType<typeof createPasswordChangeSchema>>;

export default function SettingsPage() {
  const { user, refreshUser } = useAuth();
  const { t, language, setLanguage, isRTL } = useLanguage();
  const canReadSettings = !!user && hasPermission(user.role, "settings:read");
  const canManageCustomFields = !!user && hasPermission(user.role, "settings:update");
  const [activeTab, setActiveTab] = useState("profile");
  const [isSavingProfile, setIsSavingProfile] = useState(false);
  const [isSavingPassword, setIsSavingPassword] = useState(false);
  const [smtp, setSmtp] = useState({
    host: "",
    port: 587,
    secure: false,
    user: "",
    pass: "",
    fromName: "",
    fromEmail: "",
  });
  const [testTo, setTestTo] = useState("");
  const [isLoadingSmtp, setIsLoadingSmtp] = useState(false);
  const [isSavingSmtp, setIsSavingSmtp] = useState(false);
  const [isTestingSmtp, setIsTestingSmtp] = useState(false);
  const isEmailAdmin = user?.role === "ADMIN" || user?.role === "SUPER_ADMIN";

  const tabs = useMemo(() => {
    const base = [
      { id: "profile", labelKey: "settings.profile" as TranslationKey, icon: <User className="w-4 h-4" /> },
      { id: "security", labelKey: "settings.security" as TranslationKey, icon: <Lock className="w-4 h-4" /> },
      { id: "language", labelKey: "settings.language" as TranslationKey, icon: <Globe className="w-4 h-4" /> },
      { id: "notifications", labelKey: "settings.notifications" as TranslationKey, icon: <Bell className="w-4 h-4" /> },
    ] as Array<{ id: string; labelKey?: TranslationKey; label?: string; icon: JSX.Element }>;
    if (canManageCustomFields) {
      base.push({
        id: "custom-fields",
        labelKey: "settings.customFieldsTab" as TranslationKey,
        icon: <ListOrdered className="w-4 h-4" />,
      });
    }
    if (isEmailAdmin) base.push({ id: "system-email", label: language === "ar" ? "بريد النظام" : "System Email", icon: <Mail className="w-4 h-4" /> });
    return base;
  }, [isEmailAdmin, language, canManageCustomFields]);

  const notificationRows = useMemo(
    () => [
      { eventType: "LEAD_ASSIGNED", titleKey: "settings.notifLeadTitle" as TranslationKey, descKey: "settings.notifLeadDesc" as TranslationKey, defaultOn: true },
      { eventType: "DEAL_ASSIGNED", titleKey: "settings.notifDealTitle" as TranslationKey, descKey: "settings.notifDealDesc" as TranslationKey, defaultOn: true },
      { eventType: "TASK_ASSIGNED", titleKey: "settings.notifTaskTitle" as TranslationKey, descKey: "settings.notifTaskDesc" as TranslationKey, defaultOn: true },
      { eventType: "TICKET_ASSIGNED", titleKey: "settings.notifTicketTitle" as TranslationKey, descKey: "settings.notifTicketDesc" as TranslationKey, defaultOn: false },
      { eventType: "DAILY_DIGEST", titleKey: "settings.notifWeeklyTitle" as TranslationKey, descKey: "settings.notifWeeklyDesc" as TranslationKey, defaultOn: false },
    ],
    []
  );

  const [notifStates, setNotifStates] = useState<Record<string, boolean>>({});
  const [isLoadingNotif, setIsLoadingNotif] = useState(false);
  const [savingNotifKey, setSavingNotifKey] = useState<string | null>(null);

  const profileSchema = useMemo(() => createProfileSettingsSchema(t), [t]);
  const passwordSchema = useMemo(() => createPasswordChangeSchema(t), [t]);

  const profileForm = useForm<ProfileInput>({
    resolver: zodResolver(profileSchema),
    defaultValues: { name: user?.name ?? "", phone: "" },
  });

  const passwordForm = useForm<PasswordInput>({
    resolver: zodResolver(passwordSchema),
    defaultValues: { currentPassword: "", newPassword: "", confirmPassword: "" },
  });

  const onSaveProfile = async (data: ProfileInput) => {
    if (!user) return;
    setIsSavingProfile(true);
    try {
      const res = await fetch(`/api/users/${user.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      if (!res.ok) throw new Error((await res.json()).error ?? "Failed");
      await refreshUser();
      toast.success(t("settings.toastProfileUpdated"));
    } catch (e: any) {
      toast.error(e.message);
    } finally {
      setIsSavingProfile(false);
    }
  };

  const onChangePassword = async (data: PasswordInput) => {
    if (!user) return;
    setIsSavingPassword(true);
    try {
      const res = await fetch(`/api/users/${user.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ password: data.newPassword }),
      });
      if (!res.ok) throw new Error((await res.json()).error ?? "Failed");
      toast.success(t("settings.toastPasswordUpdated"));
      passwordForm.reset();
    } catch (e: any) {
      toast.error(e.message);
    } finally {
      setIsSavingPassword(false);
    }
  };

  const langOptions = useMemo(
    () => [
      { code: "en" as const, labelKey: "settings.langEnglish" as TranslationKey, dirKey: "settings.dirLTR" as TranslationKey, flag: "🇺🇸" },
      { code: "ar" as const, labelKey: "settings.langArabic" as TranslationKey, dirKey: "settings.dirRTL" as TranslationKey, flag: "🇸🇦" },
    ],
    []
  );

  useEffect(() => {
    if (!isEmailAdmin || activeTab !== "system-email") return;
    setIsLoadingSmtp(true);
    fetch("/api/settings/email")
      .then(async (r) => {
        if (!r.ok) throw new Error((await r.json()).error ?? "Failed");
        return r.json();
      })
      .then((d) => {
        const cfg = d.data;
        setSmtp({
          host: cfg.host ?? "",
          port: Number(cfg.port ?? 587),
          secure: Boolean(cfg.secure),
          user: cfg.user ?? "",
          pass: "",
          fromName: cfg.fromName ?? "",
          fromEmail: cfg.fromEmail ?? "",
        });
      })
      .catch((e: any) => toast.error(e.message))
      .finally(() => setIsLoadingSmtp(false));
  }, [activeTab, isEmailAdmin]);

  useEffect(() => {
    if (!user || activeTab !== "notifications") return;
    setIsLoadingNotif(true);
    fetch("/api/notification-preferences")
      .then(async (r) => {
        if (!r.ok) throw new Error((await r.json()).error ?? "Failed");
        return r.json();
      })
      .then((d) => {
        const preferences = Array.isArray(d?.data?.preferences) ? d.data.preferences : [];
        const prefMap = new Map<string, boolean>();
        for (const pref of preferences) {
          if (pref?.channel === "IN_APP" && typeof pref?.eventType === "string") {
            prefMap.set(pref.eventType, Boolean(pref.isEnabled));
          }
        }
        const nextStates: Record<string, boolean> = {};
        for (const row of notificationRows) {
          nextStates[row.eventType] = prefMap.has(row.eventType)
            ? Boolean(prefMap.get(row.eventType))
            : row.defaultOn;
        }
        setNotifStates(nextStates);
      })
      .catch((e: any) => toast.error(e.message))
      .finally(() => setIsLoadingNotif(false));
  }, [activeTab, user, notificationRows]);

  const toggleNotificationPreference = async (eventType: string, currentValue: boolean) => {
    const nextValue = !currentValue;
    setNotifStates((prev) => ({ ...prev, [eventType]: nextValue }));
    setSavingNotifKey(eventType);
    try {
      const res = await fetch("/api/notification-preferences", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          eventType,
          channel: "IN_APP",
          isEnabled: nextValue,
        }),
      });
      if (!res.ok) throw new Error((await res.json()).error ?? "Failed");
    } catch (e: any) {
      setNotifStates((prev) => ({ ...prev, [eventType]: currentValue }));
      toast.error(e.message);
    } finally {
      setSavingNotifKey(null);
    }
  };

  const saveSmtp = async () => {
    setIsSavingSmtp(true);
    try {
      const res = await fetch("/api/settings/email", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(smtp),
      });
      if (!res.ok) throw new Error((await res.json()).error ?? "Failed");
      toast.success(language === "ar" ? "تم حفظ إعدادات البريد" : "Email settings saved");
      setSmtp((prev) => ({ ...prev, pass: "" }));
    } catch (e: any) {
      toast.error(e.message);
    } finally {
      setIsSavingSmtp(false);
    }
  };

  const sendTestEmail = async () => {
    if (!testTo.trim()) {
      toast.error(language === "ar" ? "أدخل بريد الاختبار" : "Enter a test recipient email");
      return;
    }
    setIsTestingSmtp(true);
    try {
      const res = await fetch("/api/settings/email", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ to: testTo.trim() }),
      });
      if (!res.ok) throw new Error((await res.json()).error ?? "Failed");
      toast.success(language === "ar" ? "تم إرسال إيميل تجريبي" : "Test email sent");
    } catch (e: any) {
      toast.error(e.message);
    } finally {
      setIsTestingSmtp(false);
    }
  };

  return (
    <AppShell breadcrumbs={[{ label: t("settings.title") }]}>
      {!canReadSettings ? (
        <div className="rounded-lg border border-border p-6 text-center text-muted-foreground">
          {language === "ar" ? "ليس لديك صلاحية الوصول إلى الإعدادات." : "You do not have permission to access settings."}
        </div>
      ) : (
      <div className="w-full min-w-0">
        <div className="mb-6">
          <h1 className="text-xl font-bold text-foreground">{t("settings.title")}</h1>
          <p className="text-sm text-muted-foreground mt-0.5">{t("settings.pageSubtitle")}</p>
        </div>

        <div className="flex flex-col sm:flex-row gap-6">
          <nav className="sm:w-48 flex-shrink-0">
            <ul className="space-y-1">
              {tabs.map((tab) => (
                <li key={tab.id}>
                  <button
                    type="button"
                    onClick={() => setActiveTab(tab.id)}
                    className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                      activeTab === tab.id
                        ? "bg-primary/10 text-primary"
                        : "text-muted-foreground hover:bg-accent hover:text-foreground"
                    }`}
                  >
                    {tab.icon}
                    {tab.label ?? (tab.labelKey ? t(tab.labelKey) : "")}
                  </button>
                </li>
              ))}
            </ul>
          </nav>

          <div className="flex-1 space-y-6">
            {activeTab === "profile" && (
              <Card>
                <CardHeader>
                  <CardTitle>{t("settings.profileInfoCard")}</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="flex items-center gap-4 mb-6">
                    <div className="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold text-xl">
                      {user ? getInitials(user.name) : "U"}
                    </div>
                    <div>
                      <p className="font-semibold text-foreground">{user?.name}</p>
                      <p className="text-sm text-muted-foreground">{user?.email}</p>
                      <p className="text-xs text-muted-foreground mt-0.5">
                        {user?.role && ROLE_LABEL_KEYS[user.role] ? t(ROLE_LABEL_KEYS[user.role]) : user?.role?.replace(/_/g, " ")}
                      </p>
                    </div>
                  </div>

                  <form noValidate onSubmit={profileForm.handleSubmit(onSaveProfile)} className="space-y-4">
                    <Input
                      label={t("settings.fullName")}
                      required
                      error={profileForm.formState.errors.name?.message}
                      {...profileForm.register("name")}
                    />
                    <Input
                      label={t("settings.email")}
                      type="email"
                      value={user?.email ?? ""}
                      disabled
                      hint={t("settings.emailDisabledHint")}
                    />
                    <Input
                      label={t("settings.phone")}
                      type="tel"
                      placeholder={t("settings.phonePlaceholder")}
                      {...profileForm.register("phone")}
                    />
                    <div className="flex justify-end">
                      <Button type="submit" loading={isSavingProfile}>
                        {t("settings.saveChanges")}
                      </Button>
                    </div>
                  </form>
                </CardContent>
              </Card>
            )}

            {activeTab === "security" && (
              <Card>
                <CardHeader>
                  <CardTitle>{t("settings.changePassword")}</CardTitle>
                </CardHeader>
                <CardContent>
                  <form noValidate onSubmit={passwordForm.handleSubmit(onChangePassword)} className="space-y-4">
                    <Input
                      label={t("settings.currentPassword")}
                      type="password"
                      required
                      error={passwordForm.formState.errors.currentPassword?.message}
                      {...passwordForm.register("currentPassword")}
                    />
                    <Input
                      label={t("settings.newPassword")}
                      type="password"
                      required
                      hint={t("settings.passwordMinHint")}
                      error={passwordForm.formState.errors.newPassword?.message}
                      {...passwordForm.register("newPassword")}
                    />
                    <Input
                      label={t("settings.confirmNewPassword")}
                      type="password"
                      required
                      error={passwordForm.formState.errors.confirmPassword?.message}
                      {...passwordForm.register("confirmPassword")}
                    />
                    <div className="flex justify-end">
                      <Button type="submit" loading={isSavingPassword}>
                        {t("settings.updatePassword")}
                      </Button>
                    </div>
                  </form>
                </CardContent>
              </Card>
            )}

            {activeTab === "language" && (
              <Card>
                <CardHeader>
                  <CardTitle>{t("settings.languageDisplay")}</CardTitle>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div>
                    <p className="text-sm font-medium text-foreground mb-3">{t("settings.interfaceLang")}</p>
                    <div className="grid grid-cols-2 gap-3">
                      {langOptions.map((lang) => (
                        <button
                          key={lang.code}
                          type="button"
                          onClick={() => {
                            setLanguage(lang.code);
                            toast.success(t("settings.toastLanguageSet", { lang: t(lang.labelKey) }));
                          }}
                          className={`flex items-center gap-3 p-4 rounded-xl border-2 transition-all ${
                            language === lang.code
                              ? "border-primary bg-primary/5"
                              : "border-border hover:border-primary/50"
                          }`}
                        >
                          <span className="text-2xl">{lang.flag}</span>
                          <div className="text-start">
                            <p className="font-semibold text-sm text-foreground">{t(lang.labelKey)}</p>
                            <p className="text-xs text-muted-foreground">{t(lang.dirKey)}</p>
                          </div>
                          {language === lang.code && (
                            <div className="ms-auto w-4 h-4 rounded-full bg-primary flex items-center justify-center">
                              <div className="w-2 h-2 rounded-full bg-white" />
                            </div>
                          )}
                        </button>
                      ))}
                    </div>
                  </div>

                  <div className="p-4 bg-muted rounded-lg">
                    <p className="text-sm font-medium text-foreground mb-1">{t("settings.currentDirectionLabel")}</p>
                    <p className="text-sm text-muted-foreground">
                      {t("settings.textDirectionIs")}{" "}
                      <span className="font-medium">{isRTL ? t("settings.rtl") : t("settings.ltr")}</span>
                    </p>
                  </div>
                </CardContent>
              </Card>
            )}

            {activeTab === "custom-fields" && canManageCustomFields && <CustomFieldsSettingsPanel />}

            {activeTab === "notifications" && (
              <Card>
                <CardHeader>
                  <CardTitle>{t("settings.notificationsCard")}</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {isLoadingNotif && (
                      <p className="text-sm text-muted-foreground">
                        {language === "ar" ? "جاري تحميل التفضيلات..." : "Loading preferences..."}
                      </p>
                    )}
                    {!isLoadingNotif && notificationRows.map((item) => {
                      const isOn = notifStates[item.eventType] ?? item.defaultOn;
                      const isSavingThis = savingNotifKey === item.eventType;
                      return (
                        <div key={item.eventType} className="flex items-center justify-between py-3 border-b border-border last:border-0">
                          <div>
                            <p className="text-sm font-medium text-foreground">{t(item.titleKey)}</p>
                            <p className="text-xs text-muted-foreground mt-0.5">{t(item.descKey)}</p>
                          </div>
                          <button
                            type="button"
                            disabled={isSavingThis}
                            onClick={() => toggleNotificationPreference(item.eventType, isOn)}
                            className={`relative w-10 h-5 rounded-full transition-colors ${
                              isOn ? "bg-primary" : "bg-muted-foreground/30"
                            } ${isSavingThis ? "opacity-60 cursor-not-allowed" : ""}`}
                          >
                            <div
                              className={`absolute top-0.5 w-4 h-4 bg-white rounded-full shadow transition-all ${
                                isOn ? "start-[1.375rem]" : "start-0.5"
                              }`}
                            />
                          </button>
                        </div>
                      );
                    })}
                  </div>
                </CardContent>
              </Card>
            )}

            {activeTab === "system-email" && isEmailAdmin && (
              <Card>
                <CardHeader>
                  <CardTitle>{language === "ar" ? "إعدادات بريد النظام (SMTP)" : "System Email Settings (SMTP)"}</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  {isLoadingSmtp ? (
                    <p className="text-sm text-muted-foreground">{language === "ar" ? "جاري التحميل..." : "Loading..."}</p>
                  ) : (
                    <>
                      <Input
                        label="SMTP Host"
                        value={smtp.host}
                        onChange={(e) => setSmtp((p) => ({ ...p, host: e.target.value }))}
                      />
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <Input
                          label="SMTP Port"
                          type="number"
                          value={String(smtp.port)}
                          onChange={(e) => setSmtp((p) => ({ ...p, port: Number(e.target.value) || 0 }))}
                        />
                        <Input
                          label={language === "ar" ? "مستخدم SMTP" : "SMTP User"}
                          value={smtp.user}
                          onChange={(e) => setSmtp((p) => ({ ...p, user: e.target.value }))}
                        />
                      </div>
                      <Input
                        label={language === "ar" ? "كلمة مرور SMTP" : "SMTP Password"}
                        type="password"
                        value={smtp.pass}
                        onChange={(e) => setSmtp((p) => ({ ...p, pass: e.target.value }))}
                        hint={language === "ar" ? "اتركه فارغًا للإبقاء على كلمة المرور الحالية" : "Leave empty to keep the current password"}
                      />
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <Input
                          label={language === "ar" ? "اسم المرسل" : "From Name"}
                          value={smtp.fromName}
                          onChange={(e) => setSmtp((p) => ({ ...p, fromName: e.target.value }))}
                        />
                        <Input
                          label={language === "ar" ? "بريد المرسل" : "From Email"}
                          type="email"
                          value={smtp.fromEmail}
                          onChange={(e) => setSmtp((p) => ({ ...p, fromEmail: e.target.value }))}
                        />
                      </div>
                      <label className="flex items-center gap-2 text-sm text-foreground">
                        <input
                          type="checkbox"
                          checked={smtp.secure}
                          onChange={(e) => setSmtp((p) => ({ ...p, secure: e.target.checked }))}
                        />
                        {language === "ar" ? "استخدام اتصال آمن (SSL/TLS)" : "Use secure connection (SSL/TLS)"}
                      </label>
                      <div className="flex justify-end">
                        <Button onClick={saveSmtp} loading={isSavingSmtp}>
                          {language === "ar" ? "حفظ إعدادات البريد" : "Save Email Settings"}
                        </Button>
                      </div>

                      <div className="pt-4 border-t border-border space-y-3">
                        <Input
                          label={language === "ar" ? "بريد الاختبار" : "Test Recipient Email"}
                          type="email"
                          value={testTo}
                          onChange={(e) => setTestTo(e.target.value)}
                        />
                        <div className="flex justify-end">
                          <Button variant="outline" onClick={sendTestEmail} loading={isTestingSmtp}>
                            {language === "ar" ? "إرسال إيميل تجريبي" : "Send Test Email"}
                          </Button>
                        </div>
                      </div>
                    </>
                  )}
                </CardContent>
              </Card>
            )}
          </div>
        </div>
      </div>
      )}
    </AppShell>
  );
}
