import { FormEvent, useState } from "react";
import { Alert, Box, Button, Card, CardActions, CardContent, CircularProgress, Stack, TextField, Typography } from "@mui/material";
import SearchIcon from "@mui/icons-material/Search";
import AddIcon from "@mui/icons-material/Add";
import { useNavigate } from "react-router-dom";
import { api } from "../api";

type DiscoveredJob = { id: string; title: string; company?: string; location?: string; modifiedAt?: string; url: string; source: string; countryCode: string; };

export default function JobDiscoveryPage() {
  const navigate = useNavigate();
  const [query, setQuery] = useState("");
  const [location, setLocation] = useState("");
  const [jobs, setJobs] = useState<DiscoveredJob[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const search = async (event: FormEvent) => {
    event.preventDefault(); setLoading(true); setError("");
    try {
      const response = await api.get<DiscoveredJob[]>("/job-discovery/search", { params: { q: query || undefined, location: location || undefined } });
      setJobs(response.data ?? []);
    } catch { setError("NAV job discovery is temporarily unavailable."); }
    finally { setLoading(false); }
  };

  return (
    <Stack spacing={3}>
      <Box component="form" onSubmit={search} sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "2fr 1fr auto" }, gap: 1.5 }}>
        <TextField label="Role or company" value={query} onChange={(event) => setQuery(event.target.value)} />
        <TextField label="Municipality" value={location} onChange={(event) => setLocation(event.target.value)} />
        <Button type="submit" variant="contained" startIcon={loading ? <CircularProgress size={18} color="inherit" /> : <SearchIcon />} disabled={loading}>Search NAV</Button>
      </Box>
      <Alert severity="info">Official Norwegian vacancies from NAV. FINN, Indeed and LinkedIn jobs can still be captured by URL.</Alert>
      {error ? <Alert severity="error">{error}</Alert> : null}
      {!loading && jobs.length === 0 ? <Typography color="text.secondary">Search recent active vacancies by role, company, or municipality.</Typography> : null}
      <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", lg: "repeat(2, minmax(0, 1fr))" }, gap: 2 }}>
        {jobs.map((job) => (
          <Card key={job.id} variant="outlined">
            <CardContent>
              <Typography variant="h6" sx={{ fontWeight: 800 }}>{job.title}</Typography>
              <Typography color="text.secondary">{[job.company, job.location].filter(Boolean).join(" · ")}</Typography>
              <Typography variant="caption" color="text.secondary">NAV · Norway{job.modifiedAt ? " · Updated " + new Date(job.modifiedAt).toLocaleDateString() : ""}</Typography>
            </CardContent>
            <CardActions>
              <Button href={job.url} target="_blank" rel="noreferrer">View listing</Button>
              <Button startIcon={<AddIcon />} onClick={() => navigate("/jobs?add=" + encodeURIComponent(job.url))}>Save to tracker</Button>
            </CardActions>
          </Card>
        ))}
      </Box>
    </Stack>
  );
}
