import React, { useEffect, useMemo, useRef, useState } from 'react';

type PipelineStage = {
    id: string;
    name: string;
    isClosed: boolean;
    winFlag: boolean;
    lossFlag: boolean;
};

type PipelineLead = {
    id: string;
    title: string;
    stageId: string;
    stage: string;
    value: string | null;
    valueNumeric: number | null;
    score: 'hot' | 'warm' | 'cold';
    owner: string;
    contactName: string | null;
    status: string;
};

type PipelineBootstrap = {
    companyName: string;
    pipelineName: string;
    leadsEndpoint: string;
    moveStageEndpointBase: string;
    csrfToken: string;
    stages: PipelineStage[];
};

function badgeClass(tone: string) {
    return {
        emerald: 'bg-emerald-100 text-emerald-700',
        amber: 'bg-amber-100 text-amber-700',
        rose: 'bg-rose-100 text-rose-700',
        blue: 'bg-blue-100 text-blue-700',
        slate: 'bg-slate-100 text-slate-700',
    }[tone] ?? 'bg-slate-100 text-slate-700';
}

export function PipelineWorkspace({ bootstrap }: { bootstrap: PipelineBootstrap }) {
    const [leads, setLeads] = useState<PipelineLead[]>([]);
    const [loading, setLoading] = useState(true);
    const boardRef = useRef<HTMLDivElement | null>(null);

    useEffect(() => {
        async function loadLeads() {
            try {
                const response = await fetch(bootstrap.leadsEndpoint, {
                    credentials: 'same-origin',
                    headers: { Accept: 'application/json' },
                });

                const json = await response.json();
                setLeads((json.data ?? []).map((lead: { id: string; title: string; stageId: string; stageName: string; value: string | null; valueNumeric: number | null; score: 'hot' | 'warm' | 'cold'; owner: string; contactName: string | null; status: string }) => ({
                    id: lead.id,
                    title: lead.title,
                    stageId: lead.stageId,
                    stage: lead.stageName,
                    value: lead.value,
                    valueNumeric: lead.valueNumeric,
                    score: lead.score,
                    owner: lead.owner,
                    contactName: lead.contactName,
                    status: lead.status,
                })));
            } finally {
                setLoading(false);
            }
        }

        void loadLeads();
    }, [bootstrap.leadsEndpoint]);

    async function moveLead(leadId: string, stageId: string) {
        const response = await fetch(`${bootstrap.moveStageEndpointBase}/${leadId}/move-stage`, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': bootstrap.csrfToken,
            },
            body: JSON.stringify({ stage_id: stageId }),
        });

        const json = await response.json();

        if (!response.ok) {
            return;
        }

        setLeads((current) =>
            current.map((lead) =>
                lead.id === leadId
                    ? {
                          ...lead,
                          stageId: json.data.stageId,
                          stage: json.data.stageName,
                      }
                    : lead
            )
        );
    }

    const columns = useMemo(
        () =>
            bootstrap.stages.map((stage) => ({
                ...stage,
                leads: leads.filter((lead) => lead.stage === stage.name),
                totalValue: leads
                    .filter((lead) => lead.stage === stage.name)
                    .reduce((sum, lead) => sum + (lead.valueNumeric ?? 0), 0),
            })),
        [leads, bootstrap.stages]
    );

    const totalPipelineValue = useMemo(
        () => leads.reduce((sum, lead) => sum + (lead.valueNumeric ?? 0), 0),
        [leads]
    );

    const openLeadCount = useMemo(
        () => leads.filter((lead) => lead.status === 'active').length,
        [leads]
    );

    const stageCount = columns.length;

    function scrollBoard(direction: 'left' | 'right') {
        if (!boardRef.current) {
            return;
        }

        const amount = Math.max(320, Math.floor(boardRef.current.clientWidth * 0.75));
        boardRef.current.scrollBy({
            left: direction === 'left' ? -amount : amount,
            behavior: 'smooth',
        });
    }

    return (
        <div className="space-y-6">
            <section className="rounded-[30px] border border-slate-200/80 bg-white p-8 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                <div className="flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between">
                    <div>
                        <p className="text-sm font-semibold uppercase tracking-[0.2em] text-emerald-600">Lead pipeline</p>
                        <h2 className="mt-2 text-3xl font-semibold tracking-tight text-slate-950">{bootstrap.pipelineName}</h2>
                        <p className="mt-3 max-w-3xl text-sm leading-7 text-slate-600">
                            Clear stage-by-stage visibility for your sales team. Review lead value, contact context, status, and move opportunities forward without the cramped card layout.
                        </p>
                    </div>

                    <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                        <div className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3">
                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Stages</p>
                            <p className="mt-2 text-xl font-semibold text-slate-950">{stageCount}</p>
                        </div>
                        <div className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3">
                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Leads</p>
                            <p className="mt-2 text-xl font-semibold text-slate-950">{leads.length}</p>
                        </div>
                        <div className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3">
                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Open Leads</p>
                            <p className="mt-2 text-xl font-semibold text-slate-950">{openLeadCount}</p>
                        </div>
                        <div className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3">
                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Pipeline Value</p>
                            <p className="mt-2 text-xl font-semibold text-slate-950">${totalPipelineValue.toFixed(2)}</p>
                        </div>
                    </div>
                </div>
            </section>

            <section className="space-y-4">
                <div className="flex flex-wrap items-center justify-between gap-3 rounded-[24px] border border-slate-200/80 bg-white px-5 py-4 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                    <div>
                        <p className="text-sm font-semibold text-slate-900">Pipeline navigation</p>
                        <p className="mt-1 text-xs uppercase tracking-[0.2em] text-slate-500">
                            Use left and right controls to move across stages
                        </p>
                    </div>
                    <div className="flex items-center gap-2">
                        <button
                            type="button"
                            onClick={() => scrollBoard('left')}
                            className="rounded-2xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 transition hover:bg-slate-50"
                        >
                            ← Left
                        </button>
                        <button
                            type="button"
                            onClick={() => scrollBoard('right')}
                            className="rounded-2xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 transition hover:bg-slate-50"
                        >
                            Right →
                        </button>
                    </div>
                </div>

                <div ref={boardRef} className="overflow-x-auto scroll-smooth">
                {loading ? (
                    <div className="mb-4 rounded-2xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-500">
                        Loading pipeline leads...
                    </div>
                ) : null}
                <div className="grid min-w-[1400px] auto-cols-[280px] grid-flow-col gap-4">
                    {columns.map((column) => (
                        <div key={column.id} className="rounded-[28px] border border-slate-200/80 bg-white p-4 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                            <div className="border-b border-slate-200 pb-4">
                                <div className="flex items-center justify-between gap-3">
                                    <div>
                                        <h3 className="text-sm font-semibold text-slate-900">{column.name}</h3>
                                        <p className="mt-1 text-xs text-slate-500">${column.totalValue.toFixed(2)} total value</p>
                                    </div>
                                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${badgeClass(column.winFlag ? 'emerald' : column.lossFlag ? 'rose' : column.isClosed ? 'amber' : 'slate')}`}>
                                        {column.leads.length}
                                    </span>
                                </div>
                            </div>

                            <div className="mt-4 space-y-3">
                                {column.leads.length > 0 ? (
                                    column.leads.map((lead) => (
                                        <div key={lead.id} className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                                            <div className="flex items-start justify-between gap-3">
                                                <div className="min-w-0">
                                                    <p className="text-sm font-semibold leading-6 text-slate-900">{lead.title}</p>
                                                    <p className="mt-1 text-xs text-slate-500">{lead.contactName ?? 'No contact linked'}</p>
                                                </div>
                                                <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${badgeClass(lead.score === 'hot' ? 'rose' : lead.score === 'warm' ? 'amber' : 'blue')}`}>
                                                    {lead.score}
                                                </span>
                                            </div>

                                            <div className="mt-4 flex flex-wrap gap-2">
                                                <span className="rounded-full bg-white px-3 py-1 text-[11px] font-semibold text-slate-600">
                                                    {lead.value ?? '$0.00'}
                                                </span>
                                                <span className={`rounded-full px-3 py-1 text-[11px] font-semibold ${badgeClass(lead.status === 'won' ? 'emerald' : lead.status === 'lost' ? 'rose' : 'slate')}`}>
                                                    {lead.status}
                                                </span>
                                            </div>

                                            <div className="mt-4 space-y-2 text-xs text-slate-500">
                                                <div className="flex items-center justify-between gap-3">
                                                    <span>Owner</span>
                                                    <span className="font-semibold text-slate-700">{lead.owner}</span>
                                                </div>
                                                <div className="flex items-center justify-between gap-3">
                                                    <span>Stage</span>
                                                    <span className="font-semibold text-slate-700">{lead.stage}</span>
                                                </div>
                                            </div>

                                            <div className="mt-4">
                                                <select
                                                    value={lead.stageId}
                                                    onChange={(event) => moveLead(lead.id, event.target.value)}
                                                    className="w-full rounded-xl border border-slate-300 bg-white px-3 py-2 text-xs font-medium text-slate-700"
                                                >
                                                    {bootstrap.stages.map((stage) => (
                                                        <option key={stage.id} value={stage.id}>
                                                            Move to {stage.name}
                                                        </option>
                                                    ))}
                                                </select>
                                            </div>
                                        </div>
                                    ))
                                ) : (
                                    <div className="rounded-2xl border border-dashed border-slate-300 bg-slate-50 px-4 py-6 text-center text-sm text-slate-500">
                                        No leads in this stage yet.
                                    </div>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
                </div>
            </section>
        </div>
    );
}

export type { PipelineBootstrap };
