import AdminLayout from '@/Layouts/AdminLayout';
import { Head, Link, router } from '@inertiajs/react';
import { FileText, ExternalLink, Edit, Trash2, MapPin, Tag, CheckCircle2, Circle, ChevronLeft, ChevronRight } from 'lucide-react';

interface CaseStudy {
    id: number;
    title: string;
    tag: string | null;
    location: string | null;
    slug: string;
    is_active: boolean;
    media?: {
        url: string;
    };
}

interface PaginationLink {
    url: string | null;
    label: string;
    active: boolean;
}

interface Props {
    caseStudies: {
        data: CaseStudy[];
        total: number;
        links: PaginationLink[];
        current_page: number;
        last_page: number;
        prev_page_url: string | null;
        next_page_url: string | null;
    };
}

export default function Index({ caseStudies }: Props) {
    const deleteCase = (id: number) => {
        if (confirm('Delete this case study?')) {
            router.delete(route('admin.case-studies.destroy', id));
        }
    };

    const caseStudyList = caseStudies.data || [];

    return (
        <AdminLayout>
            <Head title="Case Studies" />

            {/* Header */}
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-6 mb-10">
                <div>
                    <h1 className="font-display text-[1.5rem] md:text-[1.75rem] font-normal tracking-[-0.02em] text-ink leading-tight">
                        Case Studies
                    </h1>
                    <p className="mt-2 text-[13px] md:text-[14px] text-[#8C92AC]">
                        Manage your portfolio and results.
                    </p>
                </div>
                <Link
                    href={route('admin.case-studies.create')}
                    className="h-11 sm:h-9 flex items-center justify-center px-6 bg-ink text-white text-[12px] font-semibold rounded-lg hover:bg-primary transition-colors w-full sm:w-auto shadow-lg shadow-ink/10"
                >
                    New Case Study
                </Link>
            </div>

            {/* Mobile View: Cards */}
            <div className="grid gap-3 md:hidden mb-8">
                {caseStudyList.length > 0 ? caseStudyList.map((c) => (
                    <div key={c.id} className="bg-white rounded-[1.5rem] border border-[#E8E6DF] p-5 shadow-sm">
                        <div className="flex items-start gap-4 mb-4">
                            <div className="h-11 w-11 bg-[#F5F3EF] border border-[#E8E6DF] rounded-xl overflow-hidden flex-shrink-0 flex items-center justify-center">
                                {c.media?.url ? (
                                    <img src={c.media.url} className="w-full h-full object-cover" />
                                ) : (
                                    <FileText className="h-5 w-5 text-[#8C92AC]" />
                                )}
                            </div>
                            <div className="flex-1 min-w-0">
                                <p className="text-[14px] font-bold text-ink leading-tight">{c.title}</p>
                                <div className="flex items-center gap-2 mt-1.5">
                                    <span className="text-[10px] text-[#8C92AC] font-bold uppercase tracking-tighter flex items-center gap-1">
                                        <Tag className="h-3 w-3" /> {c.tag || 'Case Study'}
                                    </span>
                                </div>
                            </div>
                            <div className="flex-shrink-0 mt-1">
                                {c.is_active ? (
                                    <CheckCircle2 className="h-4 w-4 text-green-500" />
                                ) : (
                                    <Circle className="h-4 w-4 text-[#C0BDBA]" />
                                )}
                            </div>
                        </div>
                        
                        <div className="flex items-center justify-between pt-4 border-t border-[#F0EDE8]">
                            <div className="flex items-center gap-3">
                                <div className="flex items-center gap-1 text-[11px] font-bold text-[#8C92AC] uppercase tracking-tighter">
                                    <MapPin className="h-3 w-3" /> {c.location || 'Remote'}
                                </div>
                            </div>
                            <div className="flex items-center gap-2">
                                <Link href={route('admin.case-studies.edit', c.id)} className="flex items-center gap-2 px-4 py-2 bg-[#F5F3EF] text-[11px] font-bold text-ink rounded-lg border border-[#E8E6DF]">
                                    <Edit className="h-3.5 w-3.5" /> Edit
                                </Link>
                                <button onClick={() => deleteCase(c.id)} className="p-2 text-[#8C92AC] hover:text-red-500">
                                    <Trash2 className="h-4 w-4" />
                                </button>
                            </div>
                        </div>
                    </div>
                )) : (
                    <div className="bg-white rounded-[1.5rem] border border-[#E8E6DF] p-12 text-center text-[13px] text-[#8C92AC]">
                        No case studies found.
                    </div>
                )}
            </div>

            {/* Desktop View: Table */}
            <div className="hidden md:block bg-white rounded-xl border border-[#E8E6DF] overflow-hidden">
                <table className="w-full text-left">
                    <thead>
                        <tr className="border-b border-[#F0EDE8]">
                            {['Case Study', 'Status', 'Location', 'Tag', ''].map((h, i) => (
                                <th
                                    key={i}
                                    className={`px-6 py-3.5 text-[10px] font-semibold tracking-[0.14em] uppercase text-[#8C92AC]`}
                                >
                                    {h}
                                </th>
                            ))}
                        </tr>
                    </thead>
                    <tbody>
                        {caseStudyList.length > 0 ? caseStudyList.map((c) => (
                            <tr
                                key={c.id}
                                onClick={() => router.get(route('admin.case-studies.edit', c.id))}
                                className="border-b border-[#F0EDE8] last:border-0 hover:bg-[#FAFAF8] transition-colors group cursor-pointer"
                            >
                                <td className="px-6 py-4">
                                    <div className="flex items-center gap-3">
                                        <div className="h-10 w-10 bg-[#F5F3EF] border border-[#E8E6DF] rounded-lg overflow-hidden flex-shrink-0">
                                            {c.media?.url ? (
                                                <img src={c.media.url} className="w-full h-full object-cover" />
                                            ) : (
                                                <div className="w-full h-full flex items-center justify-center text-[#C0BDBA]">
                                                    <FileText className="h-4 w-4" />
                                                </div>
                                            )}
                                        </div>
                                        <div>
                                            <p className="text-[13px] font-semibold text-ink leading-tight">{c.title}</p>
                                        </div>
                                    </div>
                                </td>
                                <td className="px-6 py-4">
                                    <div className="flex items-center gap-1.5">
                                        {c.is_active ? (
                                            <>
                                                <CheckCircle2 className="h-3.5 w-3.5 text-green-500" />
                                                <span className="text-[11px] font-medium text-ink">Active</span>
                                            </>
                                        ) : (
                                            <>
                                                <Circle className="h-3.5 w-3.5 text-[#C0BDBA]" />
                                                <span className="text-[11px] font-medium text-[#8C92AC]">Draft</span>
                                            </>
                                        )}
                                    </div>
                                </td>
                                <td className="px-6 py-4">
                                    <div className="flex items-center gap-1.5 text-[12px] text-ink">
                                        <MapPin className="h-3.5 w-3.5 text-[#C0BDBA]" />
                                        {c.location || '—'}
                                    </div>
                                </td>
                                <td className="px-6 py-4">
                                    <div className="flex items-center gap-1.5 text-[12px] text-ink">
                                        <Tag className="h-3.5 w-3.5 text-[#C0BDBA]" />
                                        {c.tag || '—'}
                                    </div>
                                </td>
                                <td className="px-6 py-4 text-right" onClick={(e) => e.stopPropagation()}>
                                    <div className="flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                        <Link href={`/case-studies`} className="p-1.5 text-[#8C92AC] hover:text-ink rounded transition-colors">
                                            <ExternalLink className="h-3.5 w-3.5" />
                                        </Link>
                                        <Link href={route('admin.case-studies.edit', c.id)} className="p-1.5 text-[#8C92AC] hover:text-ink rounded transition-colors">
                                            <Edit className="h-3.5 w-3.5" />
                                        </Link>
                                        <button onClick={() => deleteCase(c.id)} className="p-1.5 text-[#8C92AC] hover:text-red-500 rounded transition-colors">
                                            <Trash2 className="h-3.5 w-3.5" />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        )) : (
                            <tr>
                                <td colSpan={5} className="px-6 py-16 text-center text-[13px] text-[#8C92AC]">
                                    No case studies yet. Build your portfolio.
                                </td>
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>

            {/* Pagination */}
            {caseStudies.last_page > 1 && (
                <div className="mt-8 flex flex-col sm:flex-row items-center justify-between gap-4">
                    <p className="text-[11px] text-[#8C92AC] font-medium">
                        Showing page {caseStudies.current_page} of {caseStudies.last_page}
                    </p>
                    <div className="flex items-center gap-1.5">
                        {caseStudies.links.map((link, i) => {
                            const isPrev = i === 0;
                            const isNext = i === caseStudies.links.length - 1;
                            
                            if (isPrev) {
                                return (
                                    <Link
                                        key={i}
                                        href={link.url || '#'}
                                        className={`p-2 rounded-lg border border-[#E8E6DF] transition-all ${!link.url ? 'opacity-30 cursor-not-allowed' : 'bg-white hover:bg-[#FAFAF8] text-ink'}`}
                                    >
                                        <ChevronLeft className="h-4 w-4" />
                                    </Link>
                                );
                            }
                            
                            if (isNext) {
                                return (
                                    <Link
                                        key={i}
                                        href={link.url || '#'}
                                        className={`p-2 rounded-lg border border-[#E8E6DF] transition-all ${!link.url ? 'opacity-30 cursor-not-allowed' : 'bg-white hover:bg-[#FAFAF8] text-ink'}`}
                                    >
                                        <ChevronRight className="h-4 w-4" />
                                    </Link>
                                );
                            }

                            const isCurrent = link.active;
                            const pageNum = parseInt(link.label);
                            const isNear = Math.abs(pageNum - caseStudies.current_page) <= 1;
                            const isEdge = pageNum === 1 || pageNum === caseStudies.last_page;

                            if (isCurrent || isNear || isEdge) {
                                return (
                                    <Link
                                        key={i}
                                        href={link.url || '#'}
                                        className={`min-w-[36px] h-[36px] flex items-center justify-center rounded-lg border text-[12px] font-semibold transition-all ${
                                            link.active
                                                ? 'bg-primary border-primary text-white'
                                                : 'bg-white border-[#E8E6DF] text-ink hover:bg-[#FAFAF8]'
                                        }`}
                                        dangerouslySetInnerHTML={{ __html: link.label }}
                                    />
                                );
                            }
                            
                            if (pageNum === caseStudies.current_page - 2 || pageNum === caseStudies.current_page + 2) {
                                return <span key={i} className="px-1 text-[#8C92AC]">...</span>;
                            }

                            return null;
                        })}
                    </div>
                </div>
            )}
        </AdminLayout>
    );
}
