"use client";

import { type ReactNode, useState, useEffect, type FormEvent } from "react";
import {
  useSystemSettings,
  useUpdateSystemSettings,
} from "@/hooks/use-system-settings";
import { useToast } from "@/providers/toast-provider";
import {
  PageHeader,
  PaperCard,
  Button,
  Input,
  Select,
  LoadingState,
  ErrorState,
} from "@/components/ui";
import { t } from "@/lib/i18n";
import {
  mockSecurityPolicy,
  mockFileUploadConfig,
  mockNotificationConfig,
  mockBrandConfig,
} from "@/mocks/fixtures";
import type {
  SystemSettingsViewModel,
  SecurityPolicy,
  FileUploadConfig,
  NotificationConfig,
  BrandConfig,
} from "@/types/view-models";

export default function SystemPage(): ReactNode {
  const { data, loading, error } = useSystemSettings();
  const { show } = useToast();
  const [updateSettings] = useUpdateSystemSettings();
  const [form, setForm] = useState<SystemSettingsViewModel | null>(null);
  const [saving, setSaving] = useState(false);
  const [securityPolicy, setSecurityPolicy] =
    useState<SecurityPolicy>(mockSecurityPolicy);
  const [fileUploadConfig, setFileUploadConfig] =
    useState<FileUploadConfig>(mockFileUploadConfig);
  const [allowedTypesText, setAllowedTypesText] = useState(
    mockFileUploadConfig.allowedTypes.join(", "),
  );
  const [notificationConfig, setNotificationConfig] =
    useState<NotificationConfig>(mockNotificationConfig);
  const [brandConfig, setBrandConfig] = useState<BrandConfig>(mockBrandConfig);

  useEffect(() => {
    if (data && !form) {
      setForm(data);
    }
  }, [data, form]);

  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!form) return;
    setSaving(true);
    try {
      await updateSettings(form);
      show("success", t("admin.system.saveSuccess"));
    } catch (err) {
      show(
        "error",
        "保存失败",
        err instanceof Error ? err.message : String(err),
      );
    } finally {
      setSaving(false);
    }
  };

  const update = (field: keyof SystemSettingsViewModel, value: string) => {
    setForm((prev) => (prev ? { ...prev, [field]: value } : prev));
  };

  return (
    <div style={{ padding: 32, maxWidth: 720, margin: "0 auto" }}>
      <PageHeader
        title={t("admin.system.title")}
        description="学校基本信息、学期与本地化设置"
      />

      <PaperCard className="p-6">
        {loading && <LoadingState />}
        {error && <ErrorState message={error.message} />}
        {form && (
          <form
            onSubmit={handleSubmit}
            style={{ display: "flex", flexDirection: "column", gap: 16 }}
          >
            <div className="grid grid-cols-2 gap-4">
              <label
                style={{ display: "flex", flexDirection: "column", gap: 4 }}
              >
                <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                  {t("admin.system.schoolName")}
                </span>
                <Input
                  type="text"
                  value={form.schoolName}
                  onChange={(e) => update("schoolName", e.target.value)}
                  required
                />
              </label>
              <label
                style={{ display: "flex", flexDirection: "column", gap: 4 }}
              >
                <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                  {t("admin.system.schoolCode")}
                </span>
                <Input
                  type="text"
                  value={form.schoolCode}
                  onChange={(e) => update("schoolCode", e.target.value)}
                  required
                  style={{ fontFamily: "var(--font-mono)" }}
                />
              </label>
              <label
                style={{ display: "flex", flexDirection: "column", gap: 4 }}
              >
                <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                  {t("admin.system.academicYear")}
                </span>
                <Input
                  type="text"
                  value={form.academicYear}
                  onChange={(e) => update("academicYear", e.target.value)}
                  placeholder="如 2025-2026"
                  required
                />
              </label>
              <label
                style={{ display: "flex", flexDirection: "column", gap: 4 }}
              >
                <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                  {t("admin.system.semester")}
                </span>
                <Select
                  value={form.semester}
                  onChange={(e) => update("semester", e.target.value)}
                >
                  <option value="first">第一学期</option>
                  <option value="second">第二学期</option>
                </Select>
              </label>
              <label
                style={{ display: "flex", flexDirection: "column", gap: 4 }}
              >
                <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                  {t("admin.system.contactEmail")}
                </span>
                <Input
                  type="email"
                  value={form.contactEmail}
                  onChange={(e) => update("contactEmail", e.target.value)}
                />
              </label>
              <label
                style={{ display: "flex", flexDirection: "column", gap: 4 }}
              >
                <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                  {t("admin.system.contactPhone")}
                </span>
                <Input
                  type="tel"
                  value={form.contactPhone}
                  onChange={(e) => update("contactPhone", e.target.value)}
                />
              </label>
              <label
                style={{
                  display: "flex",
                  flexDirection: "column",
                  gap: 4,
                  gridColumn: "span 2",
                }}
              >
                <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                  {t("admin.system.address")}
                </span>
                <Input
                  type="text"
                  value={form.address}
                  onChange={(e) => update("address", e.target.value)}
                />
              </label>
              <label
                style={{ display: "flex", flexDirection: "column", gap: 4 }}
              >
                <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                  {t("admin.system.timezone")}
                </span>
                <Select
                  value={form.timezone}
                  onChange={(e) => update("timezone", e.target.value)}
                >
                  <option value="Asia/Shanghai">Asia/Shanghai</option>
                  <option value="Asia/Hong_Kong">Asia/Hong_Kong</option>
                  <option value="UTC">UTC</option>
                </Select>
              </label>
              <label
                style={{ display: "flex", flexDirection: "column", gap: 4 }}
              >
                <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                  {t("admin.system.locale")}
                </span>
                <Select
                  value={form.locale}
                  onChange={(e) => update("locale", e.target.value)}
                >
                  <option value="zh-CN">简体中文</option>
                  <option value="en-US">English (US)</option>
                </Select>
              </label>
            </div>
            <div
              style={{
                display: "flex",
                justifyContent: "flex-end",
                marginTop: 8,
              }}
            >
              <Button variant="primary" type="submit" disabled={saving}>
                {saving ? t("admin.common.loading") : t("admin.common.save")}
              </Button>
            </div>
          </form>
        )}
      </PaperCard>

      {/* 安全策略 */}
      <PaperCard className="p-6 mt-6">
        <h3
          style={{
            fontFamily: "var(--font-serif)",
            fontSize: 16,
            color: "var(--color-ink)",
            marginBottom: 16,
          }}
        >
          {t("admin.system.security")}
        </h3>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <div className="grid grid-cols-2 gap-4">
            <label style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                {t("admin.system.passwordMinLength")}
              </span>
              <Input
                type="number"
                min={4}
                max={64}
                value={securityPolicy.passwordMinLength}
                onChange={(e) =>
                  setSecurityPolicy((prev) => ({
                    ...prev,
                    passwordMinLength: Number(e.target.value),
                  }))
                }
                style={{ width: 120 }}
              />
            </label>
            <label style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                {t("admin.system.sessionTimeout")}
              </span>
              <Input
                type="number"
                min={1}
                value={securityPolicy.sessionTimeoutMinutes}
                onChange={(e) =>
                  setSecurityPolicy((prev) => ({
                    ...prev,
                    sessionTimeoutMinutes: Number(e.target.value),
                  }))
                }
                style={{ width: 120 }}
              />
            </label>
          </div>
          <label
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              fontSize: 13,
              color: "var(--color-ink)",
            }}
          >
            <input
              type="checkbox"
              checked={securityPolicy.passwordRequireSpecial}
              onChange={(e) =>
                setSecurityPolicy((prev) => ({
                  ...prev,
                  passwordRequireSpecial: e.target.checked,
                }))
              }
            />
            {t("admin.system.passwordRequireSpecial")}
          </label>
          <label
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              fontSize: 13,
              color: "var(--color-ink)",
            }}
          >
            <input
              type="checkbox"
              checked={securityPolicy.passwordRequireUppercase}
              onChange={(e) =>
                setSecurityPolicy((prev) => ({
                  ...prev,
                  passwordRequireUppercase: e.target.checked,
                }))
              }
            />
            {t("admin.system.passwordRequireUppercase")}
          </label>
          <label
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              fontSize: 13,
              color: "var(--color-ink)",
            }}
          >
            <input
              type="checkbox"
              checked={securityPolicy.forcePasswordChange}
              onChange={(e) =>
                setSecurityPolicy((prev) => ({
                  ...prev,
                  forcePasswordChange: e.target.checked,
                }))
              }
            />
            {t("admin.system.forcePasswordChange")}
          </label>
          <div
            style={{
              display: "flex",
              justifyContent: "flex-end",
              marginTop: 4,
            }}
          >
            <Button
              variant="primary"
              onClick={() => show("success", t("admin.system.saveSuccess"))}
            >
              {t("admin.common.save")}
            </Button>
          </div>
        </div>
      </PaperCard>

      {/* 文件上传配置 */}
      <PaperCard className="p-6 mt-6">
        <h3
          style={{
            fontFamily: "var(--font-serif)",
            fontSize: 16,
            color: "var(--color-ink)",
            marginBottom: 16,
          }}
        >
          {t("admin.system.fileUpload")}
        </h3>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <label style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
              {t("admin.system.maxFileSize")}
            </span>
            <Input
              type="number"
              min={1}
              value={fileUploadConfig.maxFileSize}
              onChange={(e) =>
                setFileUploadConfig((prev) => ({
                  ...prev,
                  maxFileSize: Number(e.target.value),
                }))
              }
              style={{ width: 120 }}
            />
          </label>
          <label style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
              {t("admin.system.allowedTypes")}
            </span>
            <Input
              type="text"
              value={allowedTypesText}
              onChange={(e) => setAllowedTypesText(e.target.value)}
              placeholder="pdf, jpg, png, docx"
            />
          </label>
          <div
            style={{
              display: "flex",
              justifyContent: "flex-end",
              marginTop: 4,
            }}
          >
            <Button
              variant="primary"
              onClick={() => {
                setFileUploadConfig((prev) => ({
                  ...prev,
                  allowedTypes: allowedTypesText
                    .split(",")
                    .map((s) => s.trim())
                    .filter(Boolean),
                }));
                show("success", t("admin.system.saveSuccess"));
              }}
            >
              {t("admin.common.save")}
            </Button>
          </div>
        </div>
      </PaperCard>

      {/* 通知配置 */}
      <PaperCard className="p-6 mt-6">
        <h3
          style={{
            fontFamily: "var(--font-serif)",
            fontSize: 16,
            color: "var(--color-ink)",
            marginBottom: 16,
          }}
        >
          {t("admin.system.notification")}
        </h3>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <label
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              fontSize: 13,
              color: "var(--color-ink)",
            }}
          >
            <input
              type="checkbox"
              checked={notificationConfig.notifyNewUser}
              onChange={(e) =>
                setNotificationConfig((prev) => ({
                  ...prev,
                  notifyNewUser: e.target.checked,
                }))
              }
            />
            {t("admin.system.notifyNewUser")}
          </label>
          <label
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              fontSize: 13,
              color: "var(--color-ink)",
            }}
          >
            <input
              type="checkbox"
              checked={notificationConfig.notifyScheduleChange}
              onChange={(e) =>
                setNotificationConfig((prev) => ({
                  ...prev,
                  notifyScheduleChange: e.target.checked,
                }))
              }
            />
            {t("admin.system.notifyScheduleChange")}
          </label>
          <label
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              fontSize: 13,
              color: "var(--color-ink)",
            }}
          >
            <input
              type="checkbox"
              checked={notificationConfig.notifyAnnouncement}
              onChange={(e) =>
                setNotificationConfig((prev) => ({
                  ...prev,
                  notifyAnnouncement: e.target.checked,
                }))
              }
            />
            {t("admin.system.notifyAnnouncement")}
          </label>
          <div
            style={{
              display: "flex",
              justifyContent: "flex-end",
              marginTop: 4,
            }}
          >
            <Button
              variant="primary"
              onClick={() => show("success", t("admin.system.saveSuccess"))}
            >
              {t("admin.common.save")}
            </Button>
          </div>
        </div>
      </PaperCard>

      {/* 品牌配置 */}
      <PaperCard className="p-6 mt-6">
        <h3
          style={{
            fontFamily: "var(--font-serif)",
            fontSize: 16,
            color: "var(--color-ink)",
            marginBottom: 16,
          }}
        >
          {t("admin.system.brand")}
        </h3>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <label style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
              {t("admin.system.logoUrl")}
            </span>
            <Input
              type="text"
              value={brandConfig.logoUrl}
              onChange={(e) =>
                setBrandConfig((prev) => ({
                  ...prev,
                  logoUrl: e.target.value,
                }))
              }
            />
          </label>
          <label style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
              {t("admin.system.primaryColor")}
            </span>
            <Input
              type="color"
              value={brandConfig.primaryColor}
              onChange={(e) =>
                setBrandConfig((prev) => ({
                  ...prev,
                  primaryColor: e.target.value,
                }))
              }
              style={{ width: 60, height: 32, padding: 2 }}
            />
          </label>
          <label style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
              {t("admin.system.schoolMotto")}
            </span>
            <Input
              type="text"
              value={brandConfig.schoolMotto}
              onChange={(e) =>
                setBrandConfig((prev) => ({
                  ...prev,
                  schoolMotto: e.target.value,
                }))
              }
            />
          </label>
          <div
            style={{
              display: "flex",
              justifyContent: "flex-end",
              marginTop: 4,
            }}
          >
            <Button
              variant="primary"
              onClick={() => show("success", t("admin.system.saveSuccess"))}
            >
              {t("admin.common.save")}
            </Button>
          </div>
        </div>
      </PaperCard>
    </div>
  );
}
