import React from 'react';
import { Clock, CurrencyDollarCircle } from '@untitledui/icons';
import { Badge, BadgeWithDot, Button, PhotoWithFallback } from '../elements';

import type { JobPosting } from '../../types/api/job-posting';
import type { WebsitePhotos } from '../../types/api/website-photos';
import type { CompanyInformation } from '../../types/api/company-information';
import { resolveCtaUrls, isExternalCtaUrl } from '../../lib/cta-urls';

interface JobGalleryProps {
    jobs?: JobPosting[] | null;
    websitePhotos?: WebsitePhotos | null;
    companyInformation?: CompanyInformation | null;
    label?: string;
    title?: string;
    subtitle?: string;
    /** Optional route override for the "Send Us Your Resume" CTA. When not set, uses primary CTA URL (booking or /contact) from company info. */
    primaryCtaHrefOverride?: string;
    backgroundColor?: string;
    className?: string;
}

export const JobGallery = ({
    jobs: jobsData,
    websitePhotos,
    companyInformation,
    label = "",
    title = "",
    subtitle = "",
    primaryCtaHrefOverride,
    backgroundColor = "bg-primary",
    className = "",
}: JobGalleryProps) => {
    const resolved = companyInformation ? resolveCtaUrls(companyInformation) : null;
    const primaryCtaHref = primaryCtaHrefOverride ?? resolved?.primaryHref ?? '/contact';
    const careersPhoto = websitePhotos?.careers;
    
    // Use careers photo from API, undefined if not available (triggers gradient fallback)
    const finalHeaderImage = careersPhoto?.url;
    const finalHeaderImageAlt = careersPhoto?.alt || "Team collaboration";
    
    // Group jobs by employment_type
    const groupedJobs = React.useMemo(() => {
        const jobs = Array.isArray(jobsData) ? jobsData : [];
        if (!jobs.length) return [];
        
        const groups: Record<string, JobPosting[]> = {};
        jobs.forEach((job) => {
            const category = job.employment_type || 'General';
            if (!groups[category]) {
                groups[category] = [];
            }
            groups[category].push(job);
        });
        
        return Object.entries(groups);
    }, [jobsData]);

    return (
        <div className={`${backgroundColor} ${className}`}>
            {/* Hero Section */}
            <section className={`${backgroundColor} py-16 md:py-24`}>
                <div className="mx-auto w-full max-w-container px-4 md:px-8">
                    <div className="mx-auto flex w-full max-w-3xl flex-col items-center text-center">
                        {label && (
                            <span className="text-sm font-semibold text-brand-secondary md:text-md">{label}</span>
                        )}
                        <h1 className="mt-3 text-display-md font-semibold text-primary md:text-display-lg">
                            {title}
                        </h1>
                        <p className="mt-4 text-lg text-tertiary md:mt-6 md:text-xl">
                            {subtitle}
                        </p>
                    </div>
                </div>
            </section>

            {/* Jobs Section */}
            <section className={`${backgroundColor} py-16 md:py-24`}>
                <div className="mx-auto w-full max-w-container px-4 md:px-8">
                    <div className="mx-auto flex w-full max-w-3xl flex-col items-center text-center">
                        <Badge className="hidden md:flex" size="lg" color="brand" type="pill-color">
                            Careers
                        </Badge>
                        <Badge className="md:hidden" size="md" color="brand" type="pill-color">
                            Careers
                        </Badge>

                        <h2 className="mt-4 text-display-sm font-semibold text-primary md:text-display-md">
                            {title}
                        </h2>
                        <p className="mt-4 text-lg text-tertiary md:mt-5 md:text-xl">
                            {subtitle}
                        </p>
                    </div>

                    {/* Header Image using PhotoWithFallback */}
                    <div className="mt-12 h-60 w-full md:mt-16 md:h-140 rounded-xl overflow-hidden">
                        <PhotoWithFallback
                            photoUrl={finalHeaderImage}
                            photoAlt={finalHeaderImageAlt}
                            fallbackId="careers-header"
                            className="size-full object-cover"
                        />
                    </div>

                    {groupedJobs.length > 0 ? (
                        <div className="mx-auto mt-12 max-w-3xl md:mt-16">
                            <ul className="flex flex-col gap-8 md:gap-16">
                                {groupedJobs.map(([category, categoryJobs]) => (
                                    <li key={category}>
                                        <h2 className="text-lg font-semibold text-primary md:text-xl">{category}</h2>
                                        <ul className="mt-5 flex flex-col gap-4 md:mt-8 md:gap-6">
                                            {categoryJobs.map((job, index) => {
                                                const description = job.description_markdown?.replace(/[#*\[\]()]/g, '').trim() || '';
                                                
                                                return (
                                                    <li key={job.id || index}>
                                                        <a
                                                            href={`/careers/${job.slug}`}
                                                            className="flex flex-col rounded-2xl bg-primary p-6 ring-1 ring-secondary ring-inset hover:ring-2 hover:ring-brand-secondary transition-all"
                                                        >
                                                            <div className="flex flex-col items-start gap-2 md:flex-row">
                                                                <h3 className="text-md font-semibold text-primary">{job.title}</h3>

                                                                <div className="flex flex-1 gap-2 md:flex-row-reverse md:justify-between">
                                                                    {job.location && (
                                                                        <Badge color="gray" size="md" type="modern">
                                                                            {job.location}
                                                                        </Badge>
                                                                    )}

                                                                    {job.employment_type && (
                                                                        <BadgeWithDot color="brand" size="md" type="modern">
                                                                            {job.employment_type}
                                                                        </BadgeWithDot>
                                                                    )}
                                                                </div>
                                                            </div>

                                                            <p className="mt-2 text-md text-tertiary line-clamp-2">
                                                                {description}
                                                            </p>

                                                            <div className="mt-5 flex gap-4">
                                                                {job.employment_type && (
                                                                    <div className="flex items-center gap-1.5">
                                                                        <Clock size={20} className="text-fg-quaternary" />
                                                                        <span className="text-sm font-medium text-tertiary">{job.employment_type}</span>
                                                                    </div>
                                                                )}
                                                                {job.salary_range && (
                                                                    <div className="flex items-center gap-1.5">
                                                                        <CurrencyDollarCircle size={20} className="text-fg-quaternary" />
                                                                        <span className="text-sm font-medium text-tertiary">{job.salary_range}</span>
                                                                    </div>
                                                                )}
                                                            </div>
                                                        </a>
                                                    </li>
                                                );
                                            })}
                                        </ul>
                                    </li>
                                ))}
                            </ul>
                        </div>
                    ) : (
                        <div className="text-center mt-12">
                            <p className="text-gray-500 mb-4">No open positions at the moment.</p>
                            <p className="text-gray-600 mb-6">We&apos;re always looking for talented individuals to join our team.</p>
                            <Button href={primaryCtaHref} target={isExternalCtaUrl(primaryCtaHref) ? '_blank' : undefined} rel={isExternalCtaUrl(primaryCtaHref) ? 'noopener noreferrer' : undefined}>Send Us Your Resume</Button>
                        </div>
                    )}
                </div>
            </section>
        </div>
    );
};
