'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { Header } from '../components/Header';
import { Footer } from '../components/Footer';
import api from '@/lib/api';

interface Job {
  id: number;
  title: string;
  slug: string;
  location: string;
  employment_type: string;
  employment_type_label: string;
  gender: string;
  gender_label: string;
  vacancy_number?: number;
  vacancy_reference_number?: string;
  deadline: string;
  deadline_formatted: string;
  status: string;
  is_expired: boolean;
  is_active: boolean;
}

interface JobStatistics {
  total: number;
  active: number;
  expired: number;
  by_employment_type: Record<string, number>;
  by_gender: Record<string, number>;
}

interface PaginationData {
  total: number;
  per_page: number;
  current_page: number;
  last_page: number;
  from: number;
  to: number;
}

export default function CareersPage() {
  const [jobs, setJobs] = useState<Job[]>([]);
  const [filteredJobs, setFilteredJobs] = useState<Job[]>([]);
  const [statistics, setStatistics] = useState<JobStatistics | null>(null);
  const [pagination, setPagination] = useState<PaginationData | null>(null);
  const [loading, setLoading] = useState(true);
  const [statsLoading, setStatsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isVisible, setIsVisible] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [showExpired, setShowExpired] = useState(true);

  useEffect(() => {
    fetchJobs();
    fetchStatistics();
  }, [currentPage, showExpired]);

  useEffect(() => {
    if (!loading) {
      setTimeout(() => setIsVisible(true), 100);
    }
  }, [loading]);

  const fetchJobs = async () => {
    try {
      setLoading(true);
      setError(null);

      const response: any = await api.getJobs({
        include_expired: showExpired,
        paginate: true,
        per_page: 10,
        page: currentPage,
      });

      let jobsData: any[] = [];
      let paginationData: PaginationData | null = null;

      if (response && typeof response === 'object') {
        if ('data' in response && Array.isArray(response.data)) {
          jobsData = response.data;
          if ('pagination' in response) {
            paginationData = response.pagination;
          }
        } else if (Array.isArray(response)) {
          jobsData = response;
        }
      }

      setJobs(jobsData);
      setFilteredJobs(jobsData);
      setPagination(paginationData);
    } catch (err: any) {
      console.error('Error fetching jobs:', err);
      setError(err?.message || 'Failed to load jobs');
    } finally {
      setLoading(false);
    }
  };

  const fetchStatistics = async () => {
    try {
      setStatsLoading(true);
      const response: any = await api.getJobStatistics();
      setStatistics(response);
    } catch (err: any) {
      console.error('Error fetching statistics:', err);
    } finally {
      setStatsLoading(false);
    }
  };

  useEffect(() => {
    if (searchTerm) {
      const filtered = jobs.filter(
        (job) =>
          job.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
          job.location.toLowerCase().includes(searchTerm.toLowerCase()) ||
          (job.vacancy_reference_number &&
            job.vacancy_reference_number.toLowerCase().includes(searchTerm.toLowerCase()))
      );
      setFilteredJobs(filtered);
    } else {
      setFilteredJobs(jobs);
    }
  }, [searchTerm, jobs]);

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  return (
    <div className="flex min-h-screen flex-col bg-white">
      <Header />

      <section className="relative overflow-hidden border-b border-secondary-200 bg-white pt-28 pb-12 sm:pt-32 sm:pb-16">
        <div className="pointer-events-none absolute -left-24 top-10 h-64 w-64 rounded-full bg-primary-500/10 blur-3xl" />
        <div className="pointer-events-none absolute -right-16 bottom-0 h-56 w-56 rounded-full bg-navy-800/5 blur-3xl" />

        <div
          className={`relative mx-auto max-w-7xl px-4 transition-all duration-700 sm:px-6 lg:px-8 ${
            isVisible ? 'translate-y-0 opacity-100' : 'translate-y-6 opacity-0'
          }`}
        >
          <span className="inline-flex items-center gap-2 rounded-full border border-primary-500/30 bg-primary-500/10 px-4 py-1.5 text-xs font-bold uppercase tracking-widest text-primary-700">
            <span className="h-1.5 w-1.5 rounded-full bg-primary-500" />
            Get involved
          </span>

          <h1 className="mt-5 text-4xl font-black leading-tight text-neutral-900 sm:text-5xl md:text-6xl">
            Work{' '}
            <span className="relative inline-block text-primary-600">
              with us
              <svg
                className="absolute -bottom-2 left-0 w-full text-primary-400"
                viewBox="0 0 180 12"
                preserveAspectRatio="none"
                aria-hidden
              >
                <path d="M2 9C44 2 136 2 178 9" stroke="currentColor" strokeWidth="4" strokeLinecap="round" fill="none" />
              </svg>
            </span>
          </h1>

          <p className="mt-6 max-w-2xl text-lg leading-relaxed text-neutral-600">
            Join SSEOA&apos;s team delivering education and livelihood programmes in remote
            communities across Afghanistan. Apply using the guidelines in each posting.
          </p>

          {!statsLoading && statistics && (
            <div className="mt-10 overflow-hidden rounded-2xl border border-secondary-200 bg-secondary-50">
              <div className="grid grid-cols-2 md:grid-cols-4">
                <div className="border-b border-r border-secondary-200 px-5 py-5 md:border-b-0">
                  <p className="text-3xl font-black text-navy-800">{statistics.total}</p>
                  <p className="mt-1 text-sm text-neutral-500">Total jobs</p>
                </div>
                <div className="border-b border-secondary-200 px-5 py-5 md:border-b-0 md:border-r">
                  <p className="text-3xl font-black text-neutral-900">{statistics.active}</p>
                  <p className="mt-1 text-sm text-neutral-500">Active</p>
                </div>
                <div className="border-r border-secondary-200 px-5 py-5">
                  <p className="text-3xl font-black text-neutral-900">{statistics.expired}</p>
                  <p className="mt-1 text-sm text-neutral-500">Expired</p>
                </div>
                <div className="px-5 py-5">
                  <div className="flex flex-wrap gap-2">
                    {Object.entries(statistics.by_employment_type).map(([type, count]) => (
                      <span
                        key={type}
                        className="rounded-full border border-secondary-300 bg-white px-3 py-1 text-xs font-semibold text-neutral-700"
                      >
                        {type} {count}
                      </span>
                    ))}
                  </div>
                  <p className="mt-2 text-sm text-neutral-500">By contract type</p>
                </div>
              </div>
            </div>
          )}
        </div>
      </section>

      <section
        className={`flex-1 bg-white py-12 md:py-16 transition-all duration-700 ${
          isVisible ? 'translate-y-0 opacity-100' : 'translate-y-6 opacity-0'
        }`}
      >
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          {!error && !loading && (
            <div className="mb-8 flex flex-col gap-4 rounded-2xl border border-secondary-200 bg-secondary-50 p-4 md:flex-row md:items-center">
              <div className="relative flex-1">
                <input
                  type="text"
                  placeholder="Search jobs..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full rounded-lg border border-secondary-300 bg-white py-2.5 pl-10 pr-4 text-sm outline-none focus:border-primary-500 focus:ring-2 focus:ring-primary-500/20"
                />
                <svg
                  className="absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 text-neutral-400"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                  aria-hidden
                >
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
              </div>
              <label className="flex cursor-pointer items-center gap-2 text-sm font-medium text-neutral-700">
                <input
                  type="checkbox"
                  checked={showExpired}
                  onChange={(e) => {
                    setShowExpired(e.target.checked);
                    setCurrentPage(1);
                  }}
                  className="h-4 w-4 rounded border-secondary-300 text-primary-600 focus:ring-primary-500"
                />
                Show expired jobs
              </label>
              {pagination && (
                <p className="whitespace-nowrap text-sm text-neutral-500">
                  Showing <span className="font-semibold text-navy-800">{pagination.from}</span> to{' '}
                  <span className="font-semibold text-navy-800">{pagination.to}</span> of {pagination.total}
                </p>
              )}
            </div>
          )}

          {loading ? (
            <div className="py-20 text-center text-neutral-600">Loading opportunities...</div>
          ) : error ? (
            <div className="rounded-2xl border border-red-200 bg-red-50 py-16 text-center">
              <h3 className="text-2xl font-black text-neutral-900">Could not load jobs</h3>
              <p className="mt-2 text-neutral-600">{error}</p>
              <button
                type="button"
                onClick={fetchJobs}
                className="mt-6 inline-flex cursor-pointer items-center rounded-lg bg-navy-800 px-6 py-3 text-sm font-bold text-white hover:bg-navy-700"
              >
                Try again
              </button>
            </div>
          ) : filteredJobs.length === 0 ? (
            <div className="rounded-2xl border border-secondary-200 bg-secondary-50 py-16 text-center">
              <h3 className="text-2xl font-black text-neutral-900">No jobs found</h3>
              <p className="mt-2 text-neutral-600">Try adjusting your search or filter.</p>
            </div>
          ) : (
            <>
              <div className="space-y-4">
                {filteredJobs.map((job) => (
                  <Link
                    key={job.id}
                    href={`/careers/${job.slug}`}
                    className={`block cursor-pointer rounded-2xl border p-5 transition-shadow hover:shadow-md sm:p-6 ${
                      job.is_expired
                        ? 'border-secondary-200 bg-secondary-50'
                        : 'border-secondary-200 bg-white hover:border-primary-400'
                    }`}
                  >
                    <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
                      <div className="min-w-0 flex-1">
                        <div className="flex flex-wrap items-center gap-2">
                          <span className="rounded-full bg-primary-500 px-3 py-1 text-xs font-bold uppercase tracking-wide text-neutral-900">
                            {job.employment_type_label}
                          </span>
                          {job.is_expired ? (
                            <span className="rounded-full bg-amber-50 px-3 py-1 text-xs font-semibold text-amber-800">
                              Expired
                            </span>
                          ) : (
                            <span className="rounded-full bg-emerald-50 px-3 py-1 text-xs font-semibold text-emerald-700">
                              Open
                            </span>
                          )}
                          {job.vacancy_reference_number && (
                            <span className="text-xs font-medium text-neutral-400">
                              {job.vacancy_reference_number}
                            </span>
                          )}
                        </div>
                        <h2 className="mt-3 text-xl font-black text-neutral-900">{job.title}</h2>
                        <div className="mt-3 flex flex-wrap gap-x-6 gap-y-2 text-sm text-neutral-500">
                          <span>{job.location}</span>
                          <span>{job.gender_label}</span>
                          {job.vacancy_number && job.vacancy_number > 1 && (
                            <span>{job.vacancy_number} positions</span>
                          )}
                        </div>
                      </div>

                      <div className="flex flex-col items-start gap-2 lg:items-end">
                        <p className="text-sm text-neutral-500">
                          Deadline <span className="font-semibold text-neutral-800">{job.deadline_formatted}</span>
                        </p>
                        <span className="inline-flex items-center gap-1.5 text-sm font-bold text-navy-800">
                          View details
                          <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                          </svg>
                        </span>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>

              {pagination && pagination.last_page > 1 && (
                <div className="mt-10 flex flex-wrap items-center justify-center gap-2">
                  <button
                    type="button"
                    onClick={() => handlePageChange(currentPage - 1)}
                    disabled={currentPage === 1}
                    className="cursor-pointer rounded-lg border border-secondary-300 px-4 py-2 text-sm font-medium text-neutral-700 hover:bg-secondary-50 disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    Previous
                  </button>
                  {Array.from({ length: Math.min(5, pagination.last_page) }, (_, i) => {
                    let pageNum;
                    if (pagination.last_page <= 5) {
                      pageNum = i + 1;
                    } else if (currentPage <= 3) {
                      pageNum = i + 1;
                    } else if (currentPage >= pagination.last_page - 2) {
                      pageNum = pagination.last_page - 4 + i;
                    } else {
                      pageNum = currentPage - 2 + i;
                    }

                    return (
                      <button
                        key={pageNum}
                        type="button"
                        onClick={() => handlePageChange(pageNum)}
                        className={`cursor-pointer rounded-lg border px-4 py-2 text-sm font-medium ${
                          currentPage === pageNum
                            ? 'border-navy-800 bg-navy-800 text-white'
                            : 'border-secondary-300 text-neutral-700 hover:bg-secondary-50'
                        }`}
                      >
                        {pageNum}
                      </button>
                    );
                  })}
                  <button
                    type="button"
                    onClick={() => handlePageChange(currentPage + 1)}
                    disabled={currentPage === pagination.last_page}
                    className="cursor-pointer rounded-lg border border-secondary-300 px-4 py-2 text-sm font-medium text-neutral-700 hover:bg-secondary-50 disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    Next
                  </button>
                </div>
              )}
            </>
          )}
        </div>
      </section>

      <Footer />
    </div>
  );
}
