import React, { useEffect, useMemo, useState } from "react";

import {
  Box,
  Button,
  Checkbox,
  FormControl,
  FormControlLabel,
  InputLabel,
  MenuItem,
  Paper,
  Popover,
  Select,
  Tab,
  Tabs,
  TextField,
  Typography,
} from "@mui/material";

import { useNavigate } from "react-router-dom";

import { JobTableColumns } from "./JobTable";
import ImportExportJobs from "./ImportExportJobs";
import GoogleAuthCard from "./GoogleAuthCard";
import EmailProviderConnections from "./EmailProviderConnections";
import RulesSettingsCard from "./RulesSettingsCard";
import BackupCard from "./BackupCard";
import QuickCaptureCard from "./QuickCaptureCard";
import AuthStatusCard from "./AuthStatusCard";
import { ThemeModePref } from "../themePrefs";
import { useI18n } from "../i18n/I18nProvider";

interface Props {
  pageSize: 15 | 20 | 25;
  onPageSizeChange: (n: 15 | 20 | 25) => void;
  columns: JobTableColumns;
  onColumnsChange: (next: JobTableColumns) => void;
  themeMode: ThemeModePref;
  onThemeModeChange: (v: ThemeModePref) => void;
  accentColor: string;
  onAccentColorChange: (v: string) => void;
  onResetAccentColor: () => void;
}

function TabPanel({ value, index, children }: { value: number; index: number; children: React.ReactNode }) {
  if (value !== index) return null;
  return <Box sx={{ mt: 2 }}>{children}</Box>;
}

const ACCENTS = ["#6366f1", "#22d3ee", "#2563eb", "#8b5cf6", "#15803d", "#16a34a", "#0f766e", "#f97316"];
const NOTIFICATION_PREFS_KEY = "settings.notificationPrefs";

type NotificationPrefs = {
  emailFollowUpReminders: boolean;
  emailGhostedJobAlerts: boolean;
  inAppReminderHighlights: boolean;
};

function loadNotificationPrefs(): NotificationPrefs {
  try {
    const raw = window.localStorage.getItem(NOTIFICATION_PREFS_KEY);
    if (!raw) {
      return {
        emailFollowUpReminders: true,
        emailGhostedJobAlerts: true,
        inAppReminderHighlights: true,
      };
    }
    return {
      emailFollowUpReminders: true,
      emailGhostedJobAlerts: true,
      inAppReminderHighlights: true,
      ...JSON.parse(raw),
    };
  } catch {
    return {
      emailFollowUpReminders: true,
      emailGhostedJobAlerts: true,
      inAppReminderHighlights: true,
    };
  }
}

export default function SettingsView({
  pageSize,
  onPageSizeChange,
  columns,
  onColumnsChange,
  themeMode,
  onThemeModeChange,
  accentColor,
  onAccentColorChange,
  onResetAccentColor,
}: Props) {
  const navigate = useNavigate();
  const [tab, setTab] = useState(0);
  const { language, setLanguage, t } = useI18n();
  const [accentAnchor, setAccentAnchor] = useState<HTMLElement | null>(null);
  const [accentDraft, setAccentDraft] = useState(accentColor);
  const [notificationPrefs, setNotificationPrefs] = useState<NotificationPrefs>(() => loadNotificationPrefs());

  const accentOk = useMemo(() => /^#[0-9a-fA-F]{6}$/.test(accentColor), [accentColor]);
  const accentDraftOk = useMemo(() => /^#[0-9a-fA-F]{6}$/.test(accentDraft), [accentDraft]);

  useEffect(() => {
    setAccentDraft(accentOk ? accentColor : "#15803d");
  }, [accentColor, accentOk]);

  useEffect(() => {
    window.localStorage.setItem(NOTIFICATION_PREFS_KEY, JSON.stringify(notificationPrefs));
  }, [notificationPrefs]);

  const applyAccent = () => {
    if (!accentDraftOk) return;
    onAccentColorChange(accentDraft);
    setAccentAnchor(null);
  };

  const resetAccent = () => {
    onResetAccentColor();
    setAccentDraft("#15803d");
    setAccentAnchor(null);
  };

  return (
    <Paper sx={{ mt: 0, p: 2 }}>
      <Typography variant="h5" sx={{ mb: 1, fontWeight: 900 }}>
        {t("settingsTitle")}
      </Typography>
      <Typography sx={{ color: "text.secondary", mb: 2 }}>
        {t("settingsSubtitle")}
      </Typography>

      <Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ mb: 1 }}>
        <Tab label={t("settingsTabGeneral")} />
        <Tab label={t("settingsTabFollowUps")} />
        <Tab label={t("settingsTabNotifications")} />
        <Tab label={t("settingsTabAccount")} />
        <Tab label={t("settingsTabBackup")} />
      </Tabs>

      <TabPanel value={tab} index={0}>
        <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" }, gap: 2 }}>
          <Paper sx={{ p: 2 }}>
            <Typography sx={{ fontWeight: 950, mb: 1 }}>{t("settingsAppearance")}</Typography>

            <FormControl fullWidth sx={{ mb: 2 }}>
              <InputLabel id="theme-mode-label">{t("settingsTheme")}</InputLabel>
              <Select
                labelId="theme-mode-label"
                value={themeMode}
                label={t("settingsTheme")}
                onChange={(e) => onThemeModeChange(e.target.value as ThemeModePref)}
              >
                <MenuItem value="system">{t("settingsThemeSystem")}</MenuItem>
                <MenuItem value="dark">{t("settingsThemeDark")}</MenuItem>
                <MenuItem value="light">{t("settingsThemeLight")}</MenuItem>
              </Select>
            </FormControl>

            <Box sx={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 2, flexWrap: "wrap" }}>
              <Box>
                <Typography variant="caption" sx={{ mb: 0.75, display: "block" }}>{t("settingsAccent")}</Typography>
                <Button
                  variant="outlined"
                  onClick={(e) => setAccentAnchor(e.currentTarget)}
                  sx={{ gap: 1.25, justifyContent: "flex-start", minWidth: 180 }}
                >
                  <Box sx={{ width: 20, height: 20, borderRadius: 999, bgcolor: accentOk ? accentColor : "#15803d", border: "1px solid", borderColor: "divider" }} />
                  {accentOk ? accentColor.toUpperCase() : "#15803D"}
                </Button>
              </Box>
              <Button variant="outlined" onClick={resetAccent}>
                {t("settingsReset")}
              </Button>
            </Box>

            <Popover
              open={Boolean(accentAnchor)}
              anchorEl={accentAnchor}
              onClose={() => setAccentAnchor(null)}
              anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
            >
              <Box sx={{ p: 2, width: 280, display: "grid", gap: 1.5 }}>
                <Typography sx={{ fontWeight: 900 }}>{t("settingsAccent")}</Typography>
                <input
                  aria-label={t("settingsAccent")}
                  type="color"
                  value={accentDraftOk ? accentDraft : "#15803d"}
                  onChange={(e) => setAccentDraft(e.target.value)}
                  style={{ width: "100%", height: 52, border: "none", background: "transparent", padding: 0, cursor: "pointer" }}
                />
                <TextField
                  label={t("settingsAccent")}
                  value={accentDraft}
                  onChange={(e) => setAccentDraft(e.target.value)}
                  error={!accentDraftOk}
                  helperText={accentDraftOk ? t("settingsAccentHelp") : t("settingsAccentInvalid")}
                  fullWidth
                />
                <Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
                  {ACCENTS.map((c) => (
                    <button
                      key={c}
                      type="button"
                      onClick={() => setAccentDraft(c)}
                      title={c}
                      aria-label={`${t("settingsAccent")} ${c}`}
                      style={{
                        width: 28,
                        height: 28,
                        borderRadius: 999,
                        border: c.toLowerCase() === accentDraft.toLowerCase() ? "2px solid rgba(15,23,42,0.9)" : "1px solid rgba(148,163,184,0.35)",
                        background: c,
                        cursor: "pointer",
                      }}
                    />
                  ))}
                </Box>
                <Box sx={{ display: "flex", justifyContent: "flex-end", gap: 1 }}>
                  <Button variant="text" onClick={() => setAccentAnchor(null)}>{t("cancel")}</Button>
                  <Button variant="contained" onClick={applyAccent} disabled={!accentDraftOk}>{t("save")}</Button>
                </Box>
              </Box>
            </Popover>

            <Typography variant="caption" sx={{ color: "text.secondary", display: "block", mt: 1 }}>
              {t("settingsSavedPerUser")}
            </Typography>
          </Paper>

          <Paper sx={{ p: 2 }}>
            <Typography sx={{ fontWeight: 950, mb: 1 }}>{t("settingsLanguageTitle")}</Typography>
            <Typography variant="body2" sx={{ color: "text.secondary", mb: 2 }}>
              {t("settingsLanguageBody")}
            </Typography>

            <FormControl fullWidth sx={{ mb: 2 }}>
              <InputLabel id="language-label">{t("settingsPreferredLanguage")}</InputLabel>
              <Select
                labelId="language-label"
                value={language}
                label={t("settingsPreferredLanguage")}
                onChange={(e) => setLanguage(e.target.value as "en" | "no")}
              >
                <MenuItem value="en">{t("settingsEnglish")}</MenuItem>
                <MenuItem value="no">{t("settingsNorwegian")}</MenuItem>
              </Select>
            </FormControl>

            <Typography variant="caption" sx={{ color: "text.secondary" }}>
              {t("settingsMorePagesSoon")}
            </Typography>
          </Paper>

          <Paper sx={{ p: 2, gridColumn: { xs: "1 / -1", md: "1 / -1" } }}>
            <Typography sx={{ fontWeight: 950, mb: 1 }}>{t("settingsJobs")}</Typography>

            <Box sx={{ display: "flex", gap: 3, flexWrap: "wrap" }}>
              <Box sx={{ minWidth: 240 }}>
                <Typography variant="h6" sx={{ mb: 1 }}>
                  {t("settingsPagination")}
                </Typography>
                <FormControl fullWidth>
                  <InputLabel id="page-size-label">{t("settingsRowsPerPage")}</InputLabel>
                  <Select
                    labelId="page-size-label"
                    value={pageSize}
                    label={t("settingsRowsPerPage")}
                    onChange={(e) => onPageSizeChange(e.target.value as 15 | 20 | 25)}
                  >
                    <MenuItem value={15}>15</MenuItem>
                    <MenuItem value={20}>20</MenuItem>
                    <MenuItem value={25}>25</MenuItem>
                  </Select>
                </FormControl>
              </Box>

              <Box sx={{ minWidth: 240 }}>
                <Typography variant="h6" sx={{ mb: 1 }}>
                  {t("settingsColumns")}
                </Typography>
                {(
                  [
                    ["status", t("settingsColumnStatus")],
                    ["dateApplied", t("settingsColumnDateApplied")],
                    ["daysSince", t("settingsColumnDays")],
                    ["jobUrl", t("settingsColumnJobUrl")],
                  ] as const
                ).map(([key, label]) => (
                  <FormControlLabel
                    key={key}
                    control={<Checkbox checked={columns[key]} onChange={() => onColumnsChange({ ...columns, [key]: !columns[key] })} />}
                    label={label}
                  />
                ))}
              </Box>
            </Box>

            <ImportExportJobs />
          </Paper>

          <QuickCaptureCard />
        </Box>
      </TabPanel>

      <TabPanel value={tab} index={1}>
        <RulesSettingsCard />
      </TabPanel>

      <TabPanel value={tab} index={2}>
        <Paper sx={{ p: 2 }}>
          <Typography sx={{ fontWeight: 950, mb: 0.5 }}>{t("settingsNotificationsTitle")}</Typography>
          <Typography sx={{ color: "text.secondary", mb: 2 }}>{t("settingsNotificationsBody")}</Typography>
          <Box sx={{ display: "grid", gap: 1 }}>
            <FormControlLabel
              control={<Checkbox checked={notificationPrefs.emailFollowUpReminders} onChange={(e) => setNotificationPrefs((prev) => ({ ...prev, emailFollowUpReminders: e.target.checked }))} />}
              label={t("settingsNotificationsFollowUpReminders")}
            />
            <FormControlLabel
              control={<Checkbox checked={notificationPrefs.emailGhostedJobAlerts} onChange={(e) => setNotificationPrefs((prev) => ({ ...prev, emailGhostedJobAlerts: e.target.checked }))} />}
              label={t("settingsNotificationsGhostedJobs")}
            />
            <FormControlLabel
              control={<Checkbox checked={notificationPrefs.inAppReminderHighlights} onChange={(e) => setNotificationPrefs((prev) => ({ ...prev, inAppReminderHighlights: e.target.checked }))} />}
              label={t("settingsNotificationsInAppReminders")}
            />
          </Box>
          <Typography variant="caption" sx={{ color: "text.secondary", display: "block", mt: 1.5 }}>
            {t("settingsNotificationsDelivery")}
          </Typography>
          <Box sx={{ display: "flex", gap: 1, flexWrap: "wrap", mt: 1.5 }}>
            <Button variant="outlined" onClick={() => navigate("/reminders")}>{t("settingsOpenReminderInbox")}</Button>
            <Button variant="text" onClick={() => navigate("/admin/system")}>{t("settingsCheckSystemStatus")}</Button>
          </Box>
        </Paper>
      </TabPanel>

      <TabPanel value={tab} index={3}>
        <AuthStatusCard />
        <GoogleAuthCard />
        <Box sx={{ mt: 2 }}>
          <EmailProviderConnections />
        </Box>
      </TabPanel>

      <TabPanel value={tab} index={4}>
        <BackupCard />
      </TabPanel>
    </Paper>
  );
}
