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

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

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

import { JobTableColumns } from "./JobTable";
import ImportExportJobs from "./ImportExportJobs";
import RulesSettingsCard from "./RulesSettingsCard";
import BackupCard from "./BackupCard";
import QuickCaptureCard from "./QuickCaptureCard";
import AiUsageCard from "./AiUsageCard";
import AiPrivacySettingsCard from "./AiPrivacySettingsCard";
import { ThemeModePref } from "../themePrefs";
import { useI18n } from "../i18n/I18nProvider";
import { api, getApiErrorMessage } from "../api";
import { useToast } from "../toast";

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

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

function SectionCard({ title, subtitle, children }: { title: string; subtitle?: string; children: React.ReactNode }) {
  return (
    <Paper sx={{ p: "var(--app-card-padding)", borderRadius: 4, border: "none", boxShadow: "0px 1px 2px 0px rgba(15,23,42,0.04), 0px 8px 24px -12px rgba(15,23,42,0.12)" }}>
      <Typography variant="overline" sx={{ color: "text.secondary", fontWeight: 800 }}>{title}</Typography>
      {subtitle ? <Typography variant="body2" sx={{ color: "text.secondary", mt: 0.25, mb: 1.5 }}>{subtitle}</Typography> : <Box sx={{ mb: 1.5 }} />}
      {children}
    </Paper>
  );
}

type NotificationPrefs = {
  emailFollowUpRemindersEnabled: boolean;
};

export default function SettingsView({
  pageSize,
  onPageSizeChange,
  columns,
  onColumnsChange,
  themeMode,
  onThemeModeChange,
}: Props) {
  const navigate = useNavigate();
  const [tab, setTab] = useState(0);
  const { language, setLanguage, t } = useI18n();
  const { toast } = useToast();
  const [notificationPrefs, setNotificationPrefs] = useState<NotificationPrefs | null>(null);
  const [notificationError, setNotificationError] = useState<string | null>(null);
  const [savingNotifications, setSavingNotifications] = useState(false);

  useEffect(() => {
    let active = true;
    api.get<NotificationPrefs>("/notification-settings")
      .then(({ data }) => { if (active) setNotificationPrefs(data); })
      .catch((error) => { if (active) setNotificationError(getApiErrorMessage(error, t("settingsNotificationsLoadFailed"))); });
    return () => { active = false; };
  }, [t]);

  const saveNotifications = async () => {
    if (!notificationPrefs) return;
    setSavingNotifications(true);
    setNotificationError(null);
    try {
      const { data } = await api.put<NotificationPrefs>("/notification-settings", notificationPrefs);
      setNotificationPrefs(data);
      toast(t("settingsNotificationsSaved"), "success");
    } catch (error) {
      setNotificationError(getApiErrorMessage(error, t("settingsNotificationsSaveFailed")));
    } finally { setSavingNotifications(false); }
  };

  return (
    <Paper sx={{ mt: 0, p: "var(--app-card-padding)", borderRadius: 4, border: "none", boxShadow: "0px 1px 2px 0px rgba(15,23,42,0.04), 0px 8px 24px -12px rgba(15,23,42,0.12)", maxWidth: 960, mx: "auto" }}>
      <FormControl fullWidth sx={{ display: { xs: "flex", sm: "none" }, mb: 1 }}>
        <InputLabel id="settings-section-label">{t("settingsNavigation")}</InputLabel>
        <Select
          labelId="settings-section-label"
          value={tab}
          label={t("settingsNavigation")}
          onChange={(event) => setTab(Number(event.target.value))}
        >
          <MenuItem value={0}>{t("settingsTabGeneral")}</MenuItem>
          <MenuItem value={1}>{t("settingsTabFollowUps")}</MenuItem>
          <MenuItem value={2}>{t("settingsTabNotifications")}</MenuItem>
          <MenuItem value={3}>{t("settingsTabBackup")}</MenuItem>
        </Select>
      </FormControl>

      <Tabs value={tab} onChange={(_, v) => setTab(v)} variant="scrollable" scrollButtons="auto" sx={{ display: { xs: "none", sm: "flex" }, mb: 1 }}>
        <Tab label={t("settingsTabGeneral")} />
        <Tab label={t("settingsTabFollowUps")} />
        <Tab label={t("settingsTabNotifications")} />
        <Tab label={t("settingsTabBackup")} />
      </Tabs>

      <TabPanel value={tab} index={0}>
        <Box sx={{ display: "grid", gap: 2.5 }}>
          <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" }, gap: 2.5 }}>
            <SectionCard title={t("settingsAppearance")}>
              <FormControl fullWidth>
                <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>
            </SectionCard>

            <SectionCard title={t("settingsLanguageTitle")} subtitle={t("settingsLanguageBody")}>
              <FormControl fullWidth>
                <InputLabel id="language-label">{t("settingsPreferredLanguage")}</InputLabel>
                <Select
                  labelId="language-label"
                  value={language}
                  label={t("settingsPreferredLanguage")}
                  onChange={(e) => setLanguage(e.target.value as "en" | "nb")}
                >
                  <MenuItem value="en">{t("settingsEnglish")}</MenuItem>
                  <MenuItem value="nb">{t("settingsNorwegian")}</MenuItem>
                </Select>
              </FormControl>
            </SectionCard>
          </Box>

          <SectionCard title={t("settingsJobs")}>
            <Box sx={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
              <Box sx={{ minWidth: 240 }}>
                <Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 700 }}>
                  {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="subtitle2" sx={{ mb: 1, fontWeight: 700 }}>
                  {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>

            <Box sx={{ mt: 2 }}>
              <ImportExportJobs />
            </Box>
          </SectionCard>

          <AiPrivacySettingsCard />
          <AiUsageCard />
          <QuickCaptureCard />
          <SectionCard title={t("connectedAccounts")} subtitle={t("settingsConnectedAccountsBody")}>
            <Button variant="outlined" onClick={() => navigate("/settings/connected-accounts")}>{t("settingsManageConnectedAccounts")}</Button>
          </SectionCard>
        </Box>
      </TabPanel>

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

      <TabPanel value={tab} index={2}>
        <SectionCard title={t("settingsNotificationsTitle")} subtitle={t("settingsNotificationsBody")}>
          {notificationError ? <Alert severity="error" sx={{ mb: 1.5 }}>{notificationError}</Alert> : null}
          {!notificationPrefs ? <Skeleton variant="rounded" height={70} /> : <Box sx={{ display: "grid", gap: 1 }}>
            <FormControlLabel
              control={<Checkbox checked={notificationPrefs.emailFollowUpRemindersEnabled} onChange={(e) => setNotificationPrefs({ emailFollowUpRemindersEnabled: e.target.checked })} />}
              label={t("settingsNotificationsFollowUpReminders")}
            />
            <Typography variant="caption" color="text.secondary">{t("settingsNotificationsEmailBody")}</Typography>
            <Box><Button variant="contained" disabled={savingNotifications} onClick={() => void saveNotifications()}>{savingNotifications ? t("settingsSaving") : t("settingsNotificationsSave")}</Button></Box>
          </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>
          </Box>
        </SectionCard>
      </TabPanel>

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