'use client';

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

interface Policy {
  id: number;
  title: string;
  slug: string;
  type: string;
  body?: string;
  status: string;
  order: number;
  protected: boolean;
  is_authorized?: boolean;
  documents: Array<{
    id: number;
    name: string;
    file_name: string;
    mime_type: string;
    size: number;
    human_readable_size: string;
    url: string;
    created_at: string;
  }>;
  created_at: string;
  updated_at: string;
}

function padIndex(index: number) {
  return String(index + 1).padStart(2, '0');
}

export default function PoliciesPage() {
  const [policies, setPolicies] = useState<Policy[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchPolicies();
  }, []);

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

      const response: any = await api.getPolicies({
        status: 'published',
        paginate: false,
        order_by: 'order',
        order_direction: 'asc',
      });

      let policiesData: any[] = [];
      if (Array.isArray(response)) {
        policiesData = response;
      } else if (response && typeof response === 'object' && 'data' in response && Array.isArray(response.data)) {
        policiesData = response.data;
      }

      setPolicies(policiesData);
    } catch (err: any) {
      console.error('Error fetching policies:', err);
      setError(err?.message || 'Failed to load policies');
    } finally {
      setLoading(false);
    }
  };

  const query = searchTerm.trim().toLowerCase();
  const filteredPolicies = query
    ? policies.filter(
        (policy) =>
          policy.title.toLowerCase().includes(query) ||
          policy.type.toLowerCase().includes(query)
      )
    : policies;

  if (loading) {
    return (
      <div className="min-h-screen bg-white">
        <Header />
        <div className="flex min-h-[80vh] items-center justify-center px-4">
          <div className="text-center">
            <div className="mb-4 inline-block h-12 w-12 animate-spin rounded-full border-b-2 border-primary-500" />
            <p className="text-neutral-600">Loading policies…</p>
          </div>
        </div>
        <Footer />
      </div>
    );
  }

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

      <section className="relative overflow-hidden bg-white pt-28 pb-8 sm:pt-32 sm:pb-10">
        <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-4xl px-4 sm:px-6 lg:px-8">
          <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" />
            Who we are
          </span>

          <h1 className="mt-5 text-4xl font-black leading-tight text-neutral-900 sm:text-5xl md:text-6xl">
            Our{' '}
            <span className="relative inline-block text-primary-600">
              policies
              <svg
                className="absolute -bottom-2 left-0 w-full text-primary-400"
                viewBox="0 0 160 12"
                preserveAspectRatio="none"
                aria-hidden
              >
                <path d="M2 9C40 2 120 2 158 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">
            Public documents that set out how SSEOA protects communities, staff, and partners —
            and how we stay accountable in the work we do.
          </p>
        </div>
      </section>

      <section className="pb-20 sm:pb-28">
        <div className="mx-auto max-w-4xl px-4 sm:px-6 lg:px-8">
          {!error && policies.length > 0 && (
            <div className="relative mb-6">
              <input
                type="text"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                placeholder="Search by policy name or type"
                aria-label="Search policies"
                className="w-full rounded-lg border border-secondary-300 bg-white py-3 pl-11 pr-4 text-sm text-neutral-900 outline-none transition-all placeholder:text-neutral-400 focus:border-primary-500 focus:ring-2 focus:ring-primary-500/20"
              />
              <svg
                className="pointer-events-none absolute left-3.5 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>
          )}
          {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 policies</h3>
              <p className="mt-2 text-neutral-600">{error}</p>
              <button
                type="button"
                onClick={fetchPolicies}
                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>
          ) : policies.length === 0 ? (
            <div className="border-t border-secondary-200 py-16 text-center">
              <h3 className="text-2xl font-black text-neutral-900">No policies published yet</h3>
              <p className="mt-2 text-neutral-600">Check back soon for SSEOA&apos;s public policies.</p>
            </div>
          ) : filteredPolicies.length === 0 ? (
            <div className="border-t border-secondary-200 py-16 text-center">
              <h3 className="text-2xl font-black text-neutral-900">No matching policies</h3>
              <p className="mt-2 text-neutral-600">Try a different search term.</p>
            </div>
          ) : (
            <ol className="divide-y divide-secondary-200 border-y border-secondary-200">
              {filteredPolicies.map((policy, index) => (
                <li key={policy.id}>
                  <Link
                    href={`/policies/${policy.slug}`}
                    className="group flex cursor-pointer items-baseline gap-5 py-7 transition-colors sm:gap-8 sm:py-8"
                  >
                    <span className="w-10 shrink-0 font-black tabular-nums text-primary-500 sm:w-12 sm:text-xl">
                      {padIndex(index)}
                    </span>
                    <div className="min-w-0 flex-1">
                      <h2 className="text-xl font-black leading-snug text-neutral-900 transition-colors group-hover:text-primary-600 sm:text-2xl">
                        {policy.title}
                      </h2>
                      <p className="mt-1 text-sm font-semibold uppercase tracking-wide text-neutral-400">
                        {policy.type}
                      </p>
                    </div>
                    <span className="hidden shrink-0 items-center gap-1 text-sm font-bold text-navy-800 sm:inline-flex">
                      Read
                      <svg
                        className="h-4 w-4 transition-transform group-hover:translate-x-1"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                        aria-hidden
                      >
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
                      </svg>
                    </span>
                  </Link>
                </li>
              ))}
            </ol>
          )}
        </div>
      </section>

      <Footer />
    </div>
  );
}
