import { FormEvent, useEffect, useMemo, useState } from "react";
import { Alert, Box, Button, Card, CardActions, CardContent, Chip, CircularProgress, FormControlLabel, MenuItem, Stack, Switch, TextField, Typography } from "@mui/material";
import SearchIcon from "@mui/icons-material/Search";
import AddIcon from "@mui/icons-material/Add";
import BookmarkAddOutlinedIcon from "@mui/icons-material/BookmarkAddOutlined";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import RefreshIcon from "@mui/icons-material/Refresh";
import { useNavigate } from "react-router-dom";
import { api } from "../api";
import { useI18n } from "../i18n/I18nProvider";
import { useDialogActions } from "../dialogs";

type DiscoveredJob = {
  id: string;
  title: string;
  company?: string;
  location?: string;
  modifiedAt?: string;
  deadline?: string;
  url: string;
  source: string;
  sourceName?: string;
  acquisitionType?: string;
  retrievedAt?: string;
  countryCode: string;
  isNew?: boolean;
};

type SavedSearch = { id: number; name: string; query: string; location: string; isActive: boolean; lastRunAtUtc?: string; resultCount: number; dismissedCount: number };
type SavedSearchRun = { search: SavedSearch; jobs: Array<{ job: DiscoveredJob; isNew: boolean; isDismissed: boolean }> };

type SortOrder = "updated" | "deadline" | "title";

export default function JobDiscoveryPage() {
  const navigate = useNavigate();
  const { language, t } = useI18n();
  const { confirmAction } = useDialogActions();
  const [query, setQuery] = useState("");
  const [location, setLocation] = useState("");
  const [jobs, setJobs] = useState<DiscoveredJob[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [hasSearched, setHasSearched] = useState(false);
  const [lastSearch, setLastSearch] = useState({ query: "", location: "" });
  const [sortOrder, setSortOrder] = useState<SortOrder>("updated");
  const [savedSearches, setSavedSearches] = useState<SavedSearch[]>([]);
  const [savedName, setSavedName] = useState("");
  const [savingSearch, setSavingSearch] = useState(false);
  const [activeSavedSearchId, setActiveSavedSearchId] = useState<number | null>(null);
  const [updatingSavedSearchId, setUpdatingSavedSearchId] = useState<number | null>(null);

  useEffect(() => {
    let active = true;
    api.get<SavedSearch[]>("/job-discovery/saved-searches")
      .then((response) => { if (active) setSavedSearches(Array.isArray(response.data) ? response.data : []); })
      .catch(() => { /* One-off discovery remains usable if saved-search storage is unavailable. */ });
    return () => { active = false; };
  }, []);

  const runSearch = async (nextQuery: string, nextLocation: string) => {
    setLoading(true); setError(""); setJobs([]); setHasSearched(true); setLastSearch({ query: nextQuery, location: nextLocation });
    try {
      const response = await api.get<DiscoveredJob[]>("/job-discovery/search", { params: { q: nextQuery || undefined, location: nextLocation || undefined } });
      setJobs(response.data ?? []);
    } catch { setError(t("jobDiscoveryUnavailable")); }
    finally { setLoading(false); }
  };

  const search = (event: FormEvent) => {
    event.preventDefault();
    void runSearch(query.trim(), location.trim());
  };

  const saveSearch = async () => {
    const name = savedName.trim() || query.trim() || location.trim() || t("jobDiscoverySavedDefaultName");
    setSavingSearch(true); setError("");
    try {
      const response = await api.post<SavedSearch>("/job-discovery/saved-searches", { name, query: query.trim(), location: location.trim() });
      setSavedSearches((current) => [response.data, ...current]);
      setSavedName("");
    } catch { setError(t("jobDiscoverySaveSearchFailed")); }
    finally { setSavingSearch(false); }
  };

  const runSavedSearch = async (saved: SavedSearch) => {
    setLoading(true); setError(""); setHasSearched(true); setActiveSavedSearchId(saved.id);
    setQuery(saved.query); setLocation(saved.location); setLastSearch({ query: saved.query, location: saved.location });
    try {
      const response = await api.post<SavedSearchRun>(`/job-discovery/saved-searches/${saved.id}/run`);
      const visible = response.data.jobs.filter((item) => !item.isDismissed).map((item) => ({ ...item.job, isNew: item.isNew }));
      setJobs(visible);
      setSavedSearches((current) => current.map((item) => item.id === saved.id ? response.data.search : item));
    } catch { setError(t("jobDiscoveryUnavailable")); }
    finally { setLoading(false); }
  };

  const deleteSavedSearch = async (saved: SavedSearch) => {
    if (!(await confirmAction(t("jobDiscoveryDeleteSavedConfirm", { name: saved.name }), { title: t("jobDiscoveryDeleteSavedTitle"), confirmLabel: t("adminUsersDelete"), destructive: true }))) return;
    try {
      await api.delete(`/job-discovery/saved-searches/${saved.id}`);
      setSavedSearches((current) => current.filter((item) => item.id !== saved.id));
      if (activeSavedSearchId === saved.id) setActiveSavedSearchId(null);
    } catch { setError(t("jobDiscoveryDeleteSavedFailed")); }
  };

  const toggleSavedSearchAlerts = async (saved: SavedSearch) => {
    setUpdatingSavedSearchId(saved.id); setError("");
    try {
      const response = await api.patch<SavedSearch>(`/job-discovery/saved-searches/${saved.id}`, { isActive: !saved.isActive });
      setSavedSearches((current) => current.map((item) => item.id === saved.id ? response.data : item));
    } catch { setError(t("jobDiscoveryUpdateAlertsFailed")); }
    finally { setUpdatingSavedSearchId(null); }
  };

  const dismissJob = async (jobId: string) => {
    if (activeSavedSearchId === null) return;
    try {
      await api.patch(`/job-discovery/saved-searches/${activeSavedSearchId}/results/${encodeURIComponent(jobId)}/dismiss`, { isDismissed: true });
      setJobs((current) => current.filter((item) => item.id !== jobId));
      setSavedSearches((current) => current.map((item) => item.id === activeSavedSearchId ? { ...item, dismissedCount: item.dismissedCount + 1 } : item));
    } catch { setError(t("jobDiscoveryDismissFailed")); }
  };

  const sortedJobs = useMemo(() => [...jobs].sort((left, right) => {
    if (sortOrder === "title") return left.title.localeCompare(right.title);
    if (sortOrder === "deadline") {
      const leftDeadline = left.deadline ? new Date(left.deadline).getTime() : Number.MAX_SAFE_INTEGER;
      const rightDeadline = right.deadline ? new Date(right.deadline).getTime() : Number.MAX_SAFE_INTEGER;
      return leftDeadline - rightDeadline;
    }
    return new Date(right.modifiedAt || 0).getTime() - new Date(left.modifiedAt || 0).getTime();
  }), [jobs, sortOrder]);
  const formatDate = (value?: string) => value ? new Date(value).toLocaleDateString(language === "nb" ? "nb-NO" : "en") : null;

  return (
    <Stack spacing={3}>
      <Box component="form" onSubmit={search} sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "2fr 1fr auto" }, gap: 1.5 }}>
        <TextField label={t("jobDiscoveryRoleCompany")} value={query} onChange={(event) => setQuery(event.target.value)} />
        <TextField label={t("jobDiscoveryMunicipality")} value={location} onChange={(event) => setLocation(event.target.value)} />
        <Button type="submit" variant="contained" startIcon={loading ? <CircularProgress size={18} color="inherit" /> : <SearchIcon />} disabled={loading}>{t("jobDiscoverySearchNav")}</Button>
      </Box>
      <Card variant="outlined">
        <CardContent sx={{ display: "grid", gap: 1.5 }}>
          <Box>
            <Typography component="h2" variant="h6" sx={{ fontWeight: 800 }}>{t("jobDiscoverySavedSearches")}</Typography>
            <Typography variant="body2" color="text.secondary">{t("jobDiscoverySavedSearchesHelp")}</Typography>
          </Box>
          <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", sm: "minmax(0, 1fr) auto" }, gap: 1 }}>
            <TextField size="small" label={t("jobDiscoverySavedName")} value={savedName} onChange={(event) => setSavedName(event.target.value)} />
            <Button variant="outlined" startIcon={<BookmarkAddOutlinedIcon />} onClick={() => void saveSearch()} disabled={savingSearch}>{t("jobDiscoverySaveSearch")}</Button>
          </Box>
          {savedSearches.length === 0 ? <Typography variant="body2" color="text.secondary">{t("jobDiscoveryNoSavedSearches")}</Typography> : (
            <Stack spacing={1}>
              {savedSearches.map((saved) => (
                <Box key={saved.id} sx={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 1, p: 1.25, border: 1, borderColor: activeSavedSearchId === saved.id ? "primary.main" : "divider", borderRadius: 2 }}>
                  <Box sx={{ flex: "1 1 220px", minWidth: 0 }}>
                    <Typography sx={{ fontWeight: 700 }}>{saved.name}</Typography>
                    <Typography variant="caption" color="text.secondary">{[saved.query, saved.location].filter(Boolean).join(" · ") || t("jobDiscoveryAllRecent")}{saved.lastRunAtUtc ? ` · ${t("jobDiscoveryLastRun", { date: formatDate(saved.lastRunAtUtc) ?? "" })}` : ""}</Typography>
                  </Box>
                  <Chip size="small" label={t("jobDiscoveryTrackedCount", { count: saved.resultCount })} />
                  <FormControlLabel
                    sx={{ m: 0 }}
                    control={<Switch size="small" checked={saved.isActive} disabled={updatingSavedSearchId === saved.id} onChange={() => void toggleSavedSearchAlerts(saved)} />}
                    label={<Typography variant="body2">{t("jobDiscoveryAutomaticAlerts")}</Typography>}
                  />
                  <Button size="small" startIcon={<RefreshIcon />} onClick={() => void runSavedSearch(saved)} disabled={loading}>{t("jobDiscoveryRunSaved")}</Button>
                  <Button size="small" color="error" startIcon={<DeleteOutlineIcon />} onClick={() => void deleteSavedSearch(saved)}>{t("adminUsersDelete")}</Button>
                </Box>
              ))}
            </Stack>
          )}
        </CardContent>
      </Card>
      <Alert severity="info" variant="outlined" sx={{ color: "text.primary", "& .MuiAlert-icon": { color: "info.main" } }}>{t("jobDiscoverySourceHelp")}</Alert>
      {error ? <Alert severity="error" variant="outlined" sx={{ color: "text.primary" }} action={<Button color="inherit" onClick={() => void runSearch(lastSearch.query, lastSearch.location)} disabled={loading}>{t("retry")}</Button>}>{error}</Alert> : null}
      {!loading && !hasSearched ? <Typography color="text.secondary">{t("jobDiscoveryGuidance")}</Typography> : null}
      {!loading && hasSearched && !error && jobs.length === 0 ? <Alert severity="info" variant="outlined" sx={{ color: "text.primary" }}>{t("jobDiscoveryNoResults")}</Alert> : null}
      {loading ? <Typography role="status" color="text.secondary">{t("jobDiscoverySearching")}</Typography> : null}
      {jobs.length > 0 ? (
        <Box sx={{ display: "flex", gap: 2, alignItems: { xs: "stretch", sm: "center" }, justifyContent: "space-between", flexDirection: { xs: "column", sm: "row" } }}>
          <Typography role="status">{t(jobs.length === 1 ? "jobDiscoveryResultOne" : "jobDiscoveryResultMany", { count: jobs.length })}</Typography>
          <TextField select size="small" label={t("jobDiscoverySort")} value={sortOrder} onChange={(event) => setSortOrder(event.target.value as SortOrder)} sx={{ minWidth: 190 }}>
            <MenuItem value="updated">{t("jobDiscoverySortUpdated")}</MenuItem>
            <MenuItem value="deadline">{t("jobDiscoverySortDeadline")}</MenuItem>
            <MenuItem value="title">{t("jobDiscoverySortTitle")}</MenuItem>
          </TextField>
        </Box>
      ) : null}
      <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", lg: "repeat(2, minmax(0, 1fr))" }, gap: 2 }}>
        {sortedJobs.map((job) => (
          <Card key={job.id} variant="outlined" sx={{ display: "flex", flexDirection: "column" }}>
            <CardContent>
              <Stack direction="row" spacing={1} sx={{ mb: 1 }}>
                <Chip label={job.sourceName || job.source.toUpperCase()} size="small" color="primary" variant="outlined" />
                {job.isNew ? <Chip label={t("jobDiscoveryNewResult")} size="small" color="success" /> : null}
              </Stack>
              <Typography variant="h6" sx={{ fontWeight: 800 }}>{job.title}</Typography>
              <Typography color="text.secondary">{[job.company, job.location || t("jobDiscoveryLocationMissing")].filter(Boolean).join(" · ")}</Typography>
              <Stack spacing={0.25} sx={{ mt: 1 }}>
                <Typography variant="caption" color="text.secondary">
                  {job.acquisitionType === "searched" ? t("jobDiscoverySearchedListing") : t("jobDiscoverySourceTypeMissing")}
                  {formatDate(job.retrievedAt) ? ` · ${t("jobDiscoveryRetrieved", { date: formatDate(job.retrievedAt) ?? "" })}` : ""}
                </Typography>
                {formatDate(job.modifiedAt) ? <Typography variant="caption" color="text.secondary">{t("jobDiscoveryListingUpdated", { date: formatDate(job.modifiedAt) ?? "" })}</Typography> : null}
                {formatDate(job.deadline) ? <Typography variant="body2" color="text.primary">{t("jobDiscoveryDeadline", { date: formatDate(job.deadline) ?? "" })}</Typography> : null}
                <Typography variant="caption" color="text.secondary">{t("jobDiscoveryWorkArrangementMissing")}</Typography>
              </Stack>
            </CardContent>
            <CardActions sx={{ mt: "auto" }}>
              <Button href={job.url} target="_blank" rel="noreferrer">{t("jobDiscoveryViewListing")}</Button>
              <Button startIcon={<AddIcon />} onClick={() => navigate("/jobs?add=" + encodeURIComponent(job.url))}>{t("jobDiscoverySaveTracker")}</Button>
              {activeSavedSearchId !== null ? <Button color="inherit" onClick={() => void dismissJob(job.id)}>{t("jobDiscoveryDismiss")}</Button> : null}
            </CardActions>
          </Card>
        ))}
      </Box>
    </Stack>
  );
}
