'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 LeadershipMember {
  id: number;
  name: string;
  position: string;
  bio: string;
  full_bio: string;
  type: string;
  type_label: string;
  image: string;
  image_thumb?: string;
  image_medium?: string;
  image_large?: string;
  email?: string;
  linkedin?: string;
}

function defaultAvatar() {
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000/api/v1';
  const baseUrl = apiUrl.replace(/\/api\/v1\/?$/, '');
  return `${baseUrl}/images/default-avatar.svg`;
}

export default function OurLeadershipPage() {
  const [managementBoard, setManagementBoard] = useState<LeadershipMember[]>([]);
  const [seniorOfficials, setSeniorOfficials] = useState<LeadershipMember[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isVisible, setIsVisible] = useState(false);

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

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

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

      const response: any = await api.getLeadershipMembers({ status: 'active' });

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

      setManagementBoard(members.filter((m: any) => m.type === 'management'));
      setSeniorOfficials(members.filter((m: any) => m.type === 'senior'));
    } catch (err: any) {
      console.error('Error fetching leadership members:', err);
      setError(err?.message || 'Failed to load team members');
    } finally {
      setLoading(false);
    }
  };

  const LeadershipCard = ({ member }: { member: LeadershipMember }) => {
    const memberImage = member.image_large || member.image_medium || member.image || defaultAvatar();

    return (
      <Link href={`/our-leadership/${member.id}`} className="group block h-full">
        <article className="flex h-full flex-col overflow-hidden rounded-2xl border border-secondary-200 bg-white transition-shadow hover:border-primary-400 hover:shadow-md">
          <div className="aspect-[4/5] shrink-0 overflow-hidden bg-secondary-50">
            <img
              src={memberImage}
              alt={member.name}
              className="h-full w-full object-cover object-top"
            />
          </div>
          <div className="flex flex-1 flex-col p-4">
            <h3 className="line-clamp-1 text-base font-black text-neutral-900 group-hover:text-primary-600">
              {member.name}
            </h3>
            <p className="mt-0.5 line-clamp-2 min-h-[2rem] text-xs font-semibold text-primary-600">{member.position}</p>
            {member.bio && (
              <p className="mt-2 line-clamp-2 text-xs leading-relaxed text-neutral-600">
                {member.bio}
              </p>
            )}
            <span className="mt-auto pt-3 inline-flex items-center gap-1 text-xs font-bold text-navy-800">
              View profile
              <svg className="h-3.5 w-3.5" 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>
        </article>
      </Link>
    );
  };

  const MemberGrid = ({ title, members }: { title?: string; members: LeadershipMember[] }) => {
    if (members.length === 0) return null;

    return (
      <div>
        {title && (
          <h2 className="mb-8 text-2xl font-black text-neutral-900 sm:text-3xl">{title}</h2>
        )}
        <div className="grid grid-cols-2 items-stretch gap-4 md:grid-cols-3 lg:grid-cols-4 lg:gap-5">
          {members.map((member) => (
            <LeadershipCard key={member.id} member={member} />
          ))}
        </div>
      </div>
    );
  };

  return (
    <div className="min-h-screen 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" />
            About us
          </span>

          <h1 className="mt-5 text-4xl font-black leading-tight text-neutral-900 sm:text-5xl md:text-6xl">
            SSEOA{' '}
            <span className="relative inline-block text-primary-600">
              Team
              <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">
            Guided by a compact team dedicated to education, youth support, and community
            livelihoods across Afghanistan.
          </p>
        </div>
      </section>

      <section
        className={`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 space-y-16 px-4 sm:px-6 lg:px-8">
          {loading ? (
            <div className="py-20 text-center text-neutral-600">Loading team members...</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 the team</h3>
              <p className="mt-2 text-neutral-600">{error}</p>
              <button
                type="button"
                onClick={fetchLeadershipMembers}
                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>
          ) : managementBoard.length === 0 && seniorOfficials.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 team members published yet</h3>
              <p className="mt-2 text-neutral-600">Check back soon for SSEOA staff profiles.</p>
            </div>
          ) : (
            <>
              <MemberGrid members={managementBoard} />
              <MemberGrid title={managementBoard.length > 0 ? 'Senior Officials' : undefined} members={seniorOfficials} />
            </>
          )}
        </div>
      </section>

      <Footer />
    </div>
  );
}
