import { useCallback, useEffect, useMemo, useState } from 'react';
import { ArrowRight, BriefcaseBusiness, CheckCircle2, Grid3X3, Laptop, LayoutPanelTop, Route, Search, X } from 'lucide-react';
import {
  JobsPageViewModel,
  type JobsFilterDraft,
  type JobsListItem,
} from '../../../mvvm/viewmodels/JobsPageViewModel';
import { DashboardSidebar, type DashboardNavKey } from '../../dashboard/components/DashboardSidebar';
import { DashboardTopbar } from '../../dashboard/components/DashboardTopbar';
import '../../dashboard/pages/dashboard.css';
import './jobs.css';

interface JobsPageProps {
  onLogout: () => void;
  onNavigate: (target: DashboardNavKey) => void;
  onOpenJobDetail: (jobId: string, fromJobnet: boolean, returnPage?: DashboardNavKey) => void;
  onToggleTheme: () => void;
  theme: 'light' | 'dark';
}

const HOURS_OPTIONS = [2, 4, 6, 8, 10, 12, 24];
type JobsLayout = 'sidebar' | 'top';

const FALLBACK_JOBS: JobsListItem[] = [
  {
    id: 'job-1',
    title: 'Senior Frontend-udvikler',
    companyName: 'Lunar',
    occupationName: 'Frontend',
    descriptionIntro: 'Vi søger en erfaren frontend-udvikler til at lede vores nye team.',
    address: 'Kobenhavn',
    time: '',
    applicationDeadline: '',
    candidateDistance: 5,
    logoUrl: '',
    companyLogoImage: '',
    fromJobnet: false,
    isSaved: false,
    matchPercent: 98,
  },
  {
    id: 'job-2',
    title: 'UX/UI Designer (Deltid)',
    companyName: 'Pleo',
    occupationName: 'Design',
    descriptionIntro: 'Hjælp os med at skabe brugervenlige flows for vores expense management platform.',
    address: 'Kobenhavn',
    time: '',
    applicationDeadline: '',
    candidateDistance: 12,
    logoUrl: '',
    companyLogoImage: '',
    fromJobnet: false,
    isSaved: false,
    matchPercent: 95,
  },
  {
    id: 'job-3',
    title: 'React-udvikler',
    companyName: 'Zendesk',
    occupationName: 'Frontend',
    descriptionIntro: 'Bliv en del af vores kerne-team i Kobenhavn og byg software i topklasse.',
    address: 'Kobenhavn',
    time: '',
    applicationDeadline: '',
    candidateDistance: 2,
    logoUrl: '',
    companyLogoImage: '',
    fromJobnet: false,
    isSaved: false,
    matchPercent: 89,
  },
  {
    id: 'job-4',
    title: 'Full Stack Web-udvikler',
    companyName: 'Trustpilot',
    occupationName: 'Full stack',
    descriptionIntro: 'Vi leder efter en passioneret Full Stack Developer (Node.js/React).',
    address: 'Remote',
    time: '',
    applicationDeadline: '',
    candidateDistance: null,
    logoUrl: '',
    companyLogoImage: '',
    fromJobnet: false,
    isSaved: false,
    matchPercent: 85,
  },
  {
    id: 'job-5',
    title: 'Frontend-arkitekt',
    companyName: 'Novo Nordisk',
    occupationName: 'Frontend',
    descriptionIntro: 'Vær med til at designe arkitekturen for interne medicinske data-platforme.',
    address: 'Bagsvaerd',
    time: '',
    applicationDeadline: '',
    candidateDistance: 18,
    logoUrl: '',
    companyLogoImage: '',
    fromJobnet: false,
    isSaved: false,
    matchPercent: 72,
  },
  {
    id: 'job-6',
    title: 'Product Designer',
    companyName: 'Podimo',
    occupationName: 'Design',
    descriptionIntro: 'Vi mangler en skarp Product Designer til at forme fremtidens lytteoplevelse.',
    address: 'Kobenhavn',
    time: '',
    applicationDeadline: '',
    candidateDistance: 3,
    logoUrl: '',
    companyLogoImage: '',
    fromJobnet: false,
    isSaved: false,
    matchPercent: 68,
  },
];

function companyInitial(companyName: string): string {
  return companyName.trim().slice(0, 1).toUpperCase() || 'A';
}

function distanceLabel(item: JobsListItem): string {
  if (item.address.toLowerCase().includes('remote')) {
    return 'Remote';
  }
  if (typeof item.candidateDistance === 'number') {
    return `${Math.max(0, Math.round(item.candidateDistance))} km vaek`;
  }
  return item.address || 'Lokation ikke angivet';
}

function logoSource(item: JobsListItem): string {
  return item.companyLogoImage || item.logoUrl || '';
}

function JobLogo({ item }: { item: JobsListItem }) {
  const [hasImageError, setHasImageError] = useState(false);
  const source = logoSource(item);
  const showImage = source.length > 0 && !hasImageError;

  if (showImage) {
    return (
      <div className="jobs-card-logo jobs-card-logo-image-wrap">
        <img
          src={source}
          alt={item.companyName || 'Virksomhed'}
          className="jobs-card-logo-image"
          onError={() => setHasImageError(true)}
        />
      </div>
    );
  }

  return <div className="jobs-card-logo">{companyInitial(item.companyName)}</div>;
}

function toJobType(filter: JobsFilterDraft): 'fast' | 'deltid' {
  if (filter.workTypePartTime) {
    return 'deltid';
  }
  return 'fast';
}

export function JobsPage({ onLogout, onNavigate, onOpenJobDetail, onToggleTheme, theme }: JobsPageProps) {
  const viewModel = useMemo(() => new JobsPageViewModel(), []);
  const [candidate, setCandidate] = useState<{ imageUrl?: string; name: string }>({ name: 'Lasse' });
  const [search, setSearch] = useState('');
  const [layoutMode, setLayoutMode] = useState<JobsLayout>('sidebar');
  const [jobType, setJobType] = useState<'fast' | 'deltid'>('fast');
  const [maxDistance, setMaxDistance] = useState(15);
  const [partTimeHours, setPartTimeHours] = useState(24);
  const [selectedTitles, setSelectedTitles] = useState<string[]>(['Frontend-udvikler', 'UX/UI Designer']);
  const [titleSearch, setTitleSearch] = useState('');
  const [jobs, setJobs] = useState<JobsListItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [visibleCount, setVisibleCount] = useState(6);

  const loadJobs = useCallback(async () => {
    try {
      const items = await viewModel.getTabItems('jobs');
      setJobs(items);
      setVisibleCount(6);
    } catch {
      setJobs([]);
      setVisibleCount(6);
    }
  }, [viewModel]);

  useEffect(() => {
    let active = true;

    async function loadInitial() {
      try {
        const savedFilter = await viewModel.getSavedFilter();
        if (!active) {
          return;
        }

        setJobType(toJobType(savedFilter));
        setMaxDistance(savedFilter.workDistance ?? 15);
        setPartTimeHours(savedFilter.partTimeHours ?? 24);
        setSearch(savedFilter.distanceCenterName ?? '');
      } catch {
        // no-op
      }

      await loadJobs();

      if (active) {
        const profile = await viewModel.getCandidateProfile();
        if (active) {
          setCandidate(profile);
        }
        setIsLoading(false);
      }
    }

    void loadInitial();

    return () => {
      active = false;
    };
  }, [loadJobs, viewModel]);

  async function applyFilters() {
    const filter: JobsFilterDraft = {
      escoIds: [],
      workTypePermanent: jobType === 'fast',
      workTypePartTime: jobType === 'deltid',
      workDistance: maxDistance,
      partTimeHours: jobType === 'deltid' ? partTimeHours : null,
      distanceCenterName: search,
      latitude: null,
      longitude: null,
    };

    setIsLoading(true);
    try {
      const items = await viewModel.applyFiltersAndGetJobs(filter, {
        searchText: search,
        desiredTitles: selectedTitles,
      });
      setJobs(items);
      setVisibleCount(6);
    } catch {
      setJobs([]);
      setVisibleCount(6);
    }
    setIsLoading(false);
  }

  const sourceJobs = jobs.length > 0 ? jobs : FALLBACK_JOBS;
  const jobsToShow = sourceJobs.slice(0, Math.min(visibleCount, sourceJobs.length));
  const canLoadMore = visibleCount < sourceJobs.length;

  function toggleLayout() {
    setLayoutMode((current) => (current === 'sidebar' ? 'top' : 'sidebar'));
  }

  function removeTitle(value: string) {
    setSelectedTitles((current) => current.filter((title) => title !== value));
  }

  function addTitle(value: string) {
    const trimmed = value.trim();
    if (!trimmed) {
      return;
    }
    setSelectedTitles((current) => (current.includes(trimmed) ? current : [...current, trimmed]));
    setTitleSearch('');
  }

  function loadMoreJobs() {
    setVisibleCount((current) => Math.min(current + 6, sourceJobs.length));
  }

  return (
    <section className={`dash-root ${theme === 'dark' ? 'theme-dark' : ''}`}>
      <div className="dash-orb dash-orb-1" />
      <div className="dash-orb dash-orb-2" />
      <div className="dash-orb dash-orb-3" />

      <DashboardSidebar active="jobs" onNavigate={onNavigate} />

      <main className="dash-main custom-scrollbar">
        <DashboardTopbar
          name={candidate.name}
          imageUrl={candidate.imageUrl}
          onLogout={onLogout}
          theme={theme}
          onToggleTheme={onToggleTheme}
          actions={(
            <button type="button" className="jobs-layout-toggle" onClick={toggleLayout}>
              {layoutMode === 'sidebar' ? <LayoutPanelTop size={16} strokeWidth={1.8} /> : <Grid3X3 size={16} strokeWidth={1.8} />}
              <span>{layoutMode === 'sidebar' ? 'Top-layout' : 'Side-layout'}</span>
            </button>
          )}
        />

        <div className="jobs-page-head">
          <h1>Find dit naeste job</h1>
          <p>Sog og filtrer for at finde det perfekte match til din profil.</p>
        </div>

        {layoutMode === 'sidebar' ? (
          <div className="jobs-grid">
            <aside className="jobs-filter dash-card">
              <h2><BriefcaseBusiness size={18} strokeWidth={1.8} /> Filtre</h2>

              <div className="jobs-filter-block">
                <label>Sog jobtitel eller virksomhed</label>
                <div className="jobs-search-wrap">
                  <Search size={16} strokeWidth={1.8} />
                  <input
                    type="text"
                    placeholder="F.eks. Frontend Udvikler..."
                    value={search}
                    onChange={(event) => setSearch(event.target.value)}
                  />
                </div>
              </div>

              <div className="jobs-filter-block">
                <label>Onskede jobtitler</label>
                <div className="jobs-title-picker">
                  <div className="jobs-title-input-wrap">
                    {selectedTitles.map((title) => (
                      <span key={title} className="jobs-title-chip">
                        {title}
                        <button type="button" onClick={() => removeTitle(title)} aria-label={`Fjern ${title}`}>
                          <X size={12} strokeWidth={2} />
                        </button>
                      </span>
                    ))}
                    <input
                      type="text"
                      value={titleSearch}
                      onChange={(event) => setTitleSearch(event.target.value)}
                      onKeyDown={(event) => {
                        if (event.key === 'Enter') {
                          event.preventDefault();
                          addTitle(titleSearch);
                        }
                      }}
                      placeholder="Sog og tilfoj flere jobtitler..."
                    />
                  </div>
                  <div className="jobs-title-suggestions">
                    <button type="button" className="jobs-title-option active" onClick={() => addTitle('Frontend-udvikler')}>
                      <span>Frontend-udvikler</span><CheckCircle2 size={16} strokeWidth={1.8} />
                    </button>
                    <button type="button" className="jobs-title-option" onClick={() => addTitle('Backend-udvikler')}>
                      <span>Backend-udvikler</span>
                    </button>
                    <button type="button" className="jobs-title-option" onClick={() => addTitle('Full Stack-udvikler')}>
                      <span>Full Stack-udvikler</span>
                    </button>
                    <button type="button" className="jobs-title-option active" onClick={() => addTitle('UX/UI Designer')}>
                      <span>UX/UI Designer</span><CheckCircle2 size={16} strokeWidth={1.8} />
                    </button>
                    <button type="button" className="jobs-title-option" onClick={() => addTitle('Product Manager')}>
                      <span>Product Manager</span>
                    </button>
                  </div>
                </div>
              </div>

              <div className="jobs-separator" />

              <div className="jobs-filter-block">
                <label>Ansaettelsestype</label>
                <div className="jobs-radio-grid">
                  <button
                    type="button"
                    className={jobType === 'fast' ? 'jobs-radio-btn active' : 'jobs-radio-btn'}
                    onClick={() => setJobType('fast')}
                  >
                    Fast (Fuldtid)
                  </button>
                  <button
                    type="button"
                    className={jobType === 'deltid' ? 'jobs-radio-btn active' : 'jobs-radio-btn'}
                    onClick={() => setJobType('deltid')}
                  >
                    Deltid
                  </button>
                </div>
              </div>

              <div className="jobs-filter-block jobs-range-block">
                <div className="jobs-range-head">
                  <label>Maks. afstand</label>
                  <span>{maxDistance} km</span>
                </div>
                <input
                  type="range"
                  min={0}
                  max={50}
                  value={maxDistance}
                  onChange={(event) => setMaxDistance(Number(event.target.value))}
                />
                <div className="jobs-range-labels">
                  <span>0 km</span>
                  <span>50+ km</span>
                </div>
              </div>

              <div className="jobs-separator" />

              <div className="jobs-filter-block">
                <label>Timer (ved deltid)</label>
                <p>Vaelg onsket timeantal pr. uge</p>
                <div className="jobs-hours-grid">
                  {HOURS_OPTIONS.map((hour) => (
                    <button
                      key={hour}
                      type="button"
                      className={partTimeHours === hour ? 'jobs-hour-btn active' : 'jobs-hour-btn'}
                      onClick={() => setPartTimeHours(hour)}
                    >
                      {hour}
                    </button>
                  ))}
                </div>
              </div>

              <button type="button" className="jobs-apply-btn" onClick={() => void applyFilters()}>
                Opdater resultater
              </button>
            </aside>

            <section className="jobs-content">
              <div className="jobs-content-head">
                <h2>Seneste jobs</h2>
                <span>Viser {jobs.length > 0 ? jobs.length : 142} resultater</span>
              </div>

              {isLoading ? <p className="dash-loading">Indlaeser jobs...</p> : null}

              <div className="jobs-cards">
                {jobsToShow.map((item) => (
                  <article
                    key={item.id}
                    className="jobs-card"
                    role="button"
                    tabIndex={0}
                    onClick={() => onOpenJobDetail(item.id, item.fromJobnet, 'jobs')}
                    onKeyDown={(event) => {
                      if (event.key === 'Enter' || event.key === ' ') {
                        event.preventDefault();
                        onOpenJobDetail(item.id, item.fromJobnet, 'jobs');
                      }
                    }}
                  >
                    <div className="jobs-card-top">
                      <JobLogo item={item} />
                    </div>
                    <div className="jobs-card-title">
                      <h3>{item.title || 'Stilling'}</h3>
                      <p>{item.companyName || 'Virksomhed'}</p>
                    </div>
                    <p className="jobs-card-description">{item.descriptionIntro || 'Beskrivelse er ikke tilgaengelig endnu.'}</p>
                    <div className="jobs-card-bottom">
                      <div className="jobs-card-distance">
                        {item.address.toLowerCase().includes('remote') ? <Laptop size={15} strokeWidth={1.8} /> : <Route size={15} strokeWidth={1.8} />}
                        <span>{distanceLabel(item)}</span>
                      </div>
                      <button
                        type="button"
                        className="jobs-card-arrow"
                        aria-label="Se job"
                        onClick={(event) => {
                          event.stopPropagation();
                          onOpenJobDetail(item.id, item.fromJobnet, 'jobs');
                        }}
                      >
                        <ArrowRight size={16} strokeWidth={1.8} />
                      </button>
                    </div>
                  </article>
                ))}
              </div>

              <div className="jobs-load-more-wrap">
                <button type="button" className="jobs-load-more" onClick={loadMoreJobs} disabled={!canLoadMore}>
                  {canLoadMore ? 'Indlaes flere jobs' : 'Alle jobs er vist'}
                </button>
              </div>
            </section>
          </div>
        ) : (
          <section className="jobs-top-layout">
            <div className="jobs-top-filters dash-card">
              <div className="jobs-top-filter-title">
                <BriefcaseBusiness size={18} strokeWidth={1.8} />
                <h2>Filtre</h2>
              </div>

              <div className="jobs-top-controls">
                <div className="jobs-filter-block no-margin">
                  <label>Sog noegleord eller virksomhed</label>
                  <div className="jobs-search-wrap">
                    <Search size={16} strokeWidth={1.8} />
                    <input
                      type="text"
                      placeholder="F.eks. Lunar, React..."
                      value={search}
                      onChange={(event) => setSearch(event.target.value)}
                    />
                  </div>
                </div>

                <div className="jobs-filter-block no-margin">
                  <label>Ansaettelsestype</label>
                  <div className="jobs-radio-grid">
                    <button
                      type="button"
                      className={jobType === 'fast' ? 'jobs-radio-btn active' : 'jobs-radio-btn'}
                      onClick={() => setJobType('fast')}
                    >
                      Fast
                    </button>
                    <button
                      type="button"
                      className={jobType === 'deltid' ? 'jobs-radio-btn active' : 'jobs-radio-btn'}
                      onClick={() => setJobType('deltid')}
                    >
                      Deltid
                    </button>
                  </div>
                </div>

                <div className="jobs-filter-block no-margin jobs-top-range">
                  <div className="jobs-range-head">
                    <label>Maks. afstand</label>
                    <span>{maxDistance} km</span>
                  </div>
                  <input
                    type="range"
                    min={0}
                    max={50}
                    value={maxDistance}
                    onChange={(event) => setMaxDistance(Number(event.target.value))}
                  />
                </div>

                <button type="button" className="jobs-apply-btn jobs-top-apply" onClick={() => void applyFilters()}>
                  Opdater resultater
                </button>
              </div>

              <div className="jobs-filter-block no-margin">
                <label>Onskede jobtitler</label>
                <div className="jobs-title-picker">
                  <div className="jobs-title-input-wrap">
                    {selectedTitles.map((title) => (
                      <span key={title} className="jobs-title-chip">
                        {title}
                        <button type="button" onClick={() => removeTitle(title)} aria-label={`Fjern ${title}`}>
                          <X size={12} strokeWidth={2} />
                        </button>
                      </span>
                    ))}
                    <input
                      type="text"
                      value={titleSearch}
                      onChange={(event) => setTitleSearch(event.target.value)}
                      onKeyDown={(event) => {
                        if (event.key === 'Enter') {
                          event.preventDefault();
                          addTitle(titleSearch);
                        }
                      }}
                      placeholder="Sog og tilfoj flere jobtitler..."
                    />
                  </div>
                  <div className="jobs-title-suggestions">
                    <button type="button" className="jobs-title-option active" onClick={() => addTitle('Frontend-udvikler')}>
                      <span>Frontend-udvikler</span><CheckCircle2 size={16} strokeWidth={1.8} />
                    </button>
                    <button type="button" className="jobs-title-option" onClick={() => addTitle('Backend-udvikler')}>
                      <span>Backend-udvikler</span>
                    </button>
                    <button type="button" className="jobs-title-option" onClick={() => addTitle('Full Stack-udvikler')}>
                      <span>Full Stack-udvikler</span>
                    </button>
                    <button type="button" className="jobs-title-option active" onClick={() => addTitle('UX/UI Designer')}>
                      <span>UX/UI Designer</span><CheckCircle2 size={16} strokeWidth={1.8} />
                    </button>
                    <button type="button" className="jobs-title-option" onClick={() => addTitle('Product Manager')}>
                      <span>Product Manager</span>
                    </button>
                  </div>
                </div>
              </div>

              <div className="jobs-separator top-margin" />

              <div className="jobs-hours-row">
                <div>
                  <label>Timer (ved deltid)</label>
                  <p>Vaelg onsket timeantal pr. uge</p>
                </div>
                <div className="jobs-hours-grid">
                  {HOURS_OPTIONS.map((hour) => (
                    <button
                      key={hour}
                      type="button"
                      className={partTimeHours === hour ? 'jobs-hour-btn active' : 'jobs-hour-btn'}
                      onClick={() => setPartTimeHours(hour)}
                    >
                      {hour}
                    </button>
                  ))}
                </div>
              </div>
            </div>

            <section className="jobs-content">
              <div className="jobs-content-head">
                <h2>Seneste jobs</h2>
                <span>Viser {jobs.length > 0 ? jobs.length : 142} resultater</span>
              </div>

              {isLoading ? <p className="dash-loading">Indlaeser jobs...</p> : null}

              <div className="jobs-cards jobs-cards-top">
                {jobsToShow.map((item) => (
                  <article
                    key={item.id}
                    className="jobs-card"
                    role="button"
                    tabIndex={0}
                    onClick={() => onOpenJobDetail(item.id, item.fromJobnet, 'jobs')}
                    onKeyDown={(event) => {
                      if (event.key === 'Enter' || event.key === ' ') {
                        event.preventDefault();
                        onOpenJobDetail(item.id, item.fromJobnet, 'jobs');
                      }
                    }}
                  >
                    <div className="jobs-card-top">
                      <JobLogo item={item} />
                    </div>
                    <div className="jobs-card-title">
                      <h3>{item.title || 'Stilling'}</h3>
                      <p>{item.companyName || 'Virksomhed'}</p>
                    </div>
                    <p className="jobs-card-description">{item.descriptionIntro || 'Beskrivelse er ikke tilgaengelig endnu.'}</p>
                    <div className="jobs-card-bottom">
                      <div className="jobs-card-distance">
                        {item.address.toLowerCase().includes('remote') ? <Laptop size={15} strokeWidth={1.8} /> : <Route size={15} strokeWidth={1.8} />}
                        <span>{distanceLabel(item)}</span>
                      </div>
                      <button
                        type="button"
                        className="jobs-card-arrow"
                        aria-label="Se job"
                        onClick={(event) => {
                          event.stopPropagation();
                          onOpenJobDetail(item.id, item.fromJobnet, 'jobs');
                        }}
                      >
                        <ArrowRight size={16} strokeWidth={1.8} />
                      </button>
                    </div>
                  </article>
                ))}
              </div>

              <div className="jobs-load-more-wrap">
                <button type="button" className="jobs-load-more" onClick={loadMoreJobs} disabled={!canLoadMore}>
                  {canLoadMore ? 'Indlaes flere jobs' : 'Alle jobs er vist'}
                </button>
              </div>
            </section>
          </section>
        )}
      </main>
    </section>
  );
}
