import { Head, router } from '@inertiajs/react';
import { Milestone, ChevronDown, ChevronRight, CornerDownRight } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/app-layout';

interface Project {
    id: number;
    name: string;
    key: string;
}

interface TimelineMaster {
    id: number;
    parent_id: number | null;
    stage: string;
    responsibility: string | null;
    is_micro: boolean;
    is_major: boolean;
    children?: TimelineMaster[];
}

interface TimelineMapping {
    project_id: number;
    timeline_id: number;
    proposed_tcd: string | null;
    revised_tcd: string | null;
    status: string;
    remarks: string | null;
    reason_for_delay: string | null;
}

interface Props {
    projects: Project[];
    activeProjectId: number | null;
    timelines: TimelineMaster[];
    mappings: Record<number, TimelineMapping>;
}

export default function ProjectTimelinesPage({
    projects,
    activeProjectId: initialActiveProjectId,
    timelines,
    mappings,
}: Props) {
    const [selectedProjectId, setSelectedProjectId] = useState<number | ''>(
        initialActiveProjectId || '',
    );
    const [expandedStages, setExpandedStages] = useState<Record<number, boolean>>({});

    const toggleExpand = (id: number) => {
        setExpandedStages((prev) => ({
            ...prev,
            [id]: !prev[id],
        }));
    };

    const handleProjectChange = (id: number | '') => {
        setSelectedProjectId(id);
        router.get(
            '/project-timelines',
            { project_id: id },
            { preserveState: true },
        );
    };

    const handleSave = (timelineId: number) => {
        if (!selectedProjectId) {
            toast.error('Please select a project first.');
            return;
        }

        const rowElement = document.getElementById(`row-${timelineId}`);
        if (!rowElement) return;

        const proposedTcdVal = (rowElement.querySelector('[name="proposed_tcd"]') as HTMLInputElement)?.value || '';
        const revisedTcdVal = (rowElement.querySelector('[name="revised_tcd"]') as HTMLInputElement)?.value || '';
        const statusVal = (rowElement.querySelector('[name="status"]') as HTMLSelectElement)?.value || 'pending';
        const remarksVal = (rowElement.querySelector('[name="remarks"]') as HTMLInputElement)?.value || '';
        const delayVal = (rowElement.querySelector('[name="reason_for_delay"]') as HTMLInputElement)?.value || '';

        router.post(
            '/project-timelines',
            {
                project_id: selectedProjectId,
                timeline_id: timelineId,
                proposed_tcd: proposedTcdVal ? new Date(proposedTcdVal).toISOString() : null,
                revised_tcd: revisedTcdVal ? new Date(revisedTcdVal).toISOString() : null,
                status: statusVal,
                remarks: remarksVal || null,
                reason_for_delay: delayVal || null,
            },
            {
                onSuccess: () => {
                    toast.success('Timeline milestone updated successfully.');
                },
                onError: () => {
                    toast.error('Failed to update timeline milestone.');
                },
            },
        );
    };

    const renderTimelineRow = (item: TimelineMaster, isChild = false): React.ReactNode => {
        const mapping = mappings[item.id];
        const isExpanded = expandedStages[item.id];
        const hasChildren = item.children && item.children.length > 0;

        return (
            <>
                <tr
                    key={item.id}
                    id={`row-${item.id}`}
                    className={`hover:bg-zinc-50/40 dark:hover:bg-zinc-900/10 ${
                        isChild
                            ? 'bg-zinc-50/10 dark:bg-zinc-900/5'
                            : 'font-semibold bg-white dark:bg-zinc-950'
                    }`}
                >
                    <td className="p-4">
                        <div className="flex items-center gap-2">
                            {isChild ? (
                                <CornerDownRight className="size-3.5 text-zinc-400 shrink-0" />
                            ) : (
                                hasChildren && (
                                    <button
                                        type="button"
                                        onClick={() => toggleExpand(item.id)}
                                        className="text-zinc-500 hover:text-zinc-900 dark:hover:text-zinc-100"
                                    >
                                        {isExpanded ? (
                                            <ChevronDown className="size-4" />
                                        ) : (
                                            <ChevronRight className="size-4" />
                                        )}
                                    </button>
                                )
                            )}
                            <div className="min-w-0">
                                <div className="text-zinc-900 dark:text-zinc-100 truncate max-w-xs">{item.stage}</div>
                                {item.responsibility && (
                                    <span className="mt-0.5 inline-block text-[10px] text-zinc-400 font-medium">
                                        Owner: {item.responsibility}
                                    </span>
                                )}
                            </div>
                        </div>
                    </td>
                    <td className="p-4">
                        <input
                            type="date"
                            name="proposed_tcd"
                            defaultValue={
                                mapping?.proposed_tcd
                                    ? mapping.proposed_tcd.substring(0, 10)
                                    : ''
                            }
                            className="h-8 rounded border bg-transparent px-2 py-1 text-xs"
                        />
                    </td>
                    <td className="p-4">
                        <input
                            type="date"
                            name="revised_tcd"
                            defaultValue={
                                mapping?.revised_tcd
                                    ? mapping.revised_tcd.substring(0, 10)
                                    : ''
                            }
                            className="h-8 rounded border bg-transparent px-2 py-1 text-xs"
                        />
                    </td>
                    <td className="p-4">
                        <select
                            name="status"
                            defaultValue={mapping ? mapping.status : 'pending'}
                            className="h-8 rounded border bg-card px-2 py-0.5 text-xs"
                        >
                            <option value="pending">Pending</option>
                            <option value="completed">Completed</option>
                            <option value="delayed">Delayed</option>
                        </select>
                    </td>
                    <td className="p-4">
                        <input
                            type="text"
                            name="reason_for_delay"
                            placeholder="Reason if delayed..."
                            defaultValue={
                                mapping ? mapping.reason_for_delay || '' : ''
                            }
                            className="h-8 w-36 rounded border bg-transparent px-2 py-1 text-xs"
                        />
                    </td>
                    <td className="p-4">
                        <input
                            type="text"
                            name="remarks"
                            placeholder="Add comments..."
                            defaultValue={mapping ? mapping.remarks || '' : ''}
                            className="h-8 w-36 rounded border bg-transparent px-2 py-1 text-xs"
                        />
                    </td>
                    <td className="p-4 text-right">
                        <Button
                            size="sm"
                            className="h-8 rounded-lg bg-indigo-600 px-3 text-xs font-bold text-white hover:bg-indigo-700"
                            onClick={() => handleSave(item.id)}
                        >
                            Save
                        </Button>
                    </td>
                </tr>
                {hasChildren &&
                    isExpanded &&
                    item.children!.map((child) => renderTimelineRow(child, true))}
            </>
        );
    };

    return (
        <>
            <Head title="Project Milestone Updates" />
            <div className="space-y-6 p-6">
                {/* Header */}
                <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                    <div className="flex items-center gap-3">
                        <div className="flex size-10 items-center justify-center rounded-xl bg-indigo-50 text-indigo-600 dark:bg-indigo-950/50 dark:text-indigo-400">
                            <Milestone className="size-5" />
                        </div>
                        <div>
                            <h1 className="text-xl font-extrabold text-zinc-900 dark:text-zinc-50">
                                Project Milestone Updates
                            </h1>
                            <p className="text-xs text-zinc-500 font-medium">
                                Maintain targets, proposed dates, and delay logs for project development timelines.
                            </p>
                        </div>
                    </div>
                </div>

                {/* Project Selector Card */}
                <Card className="rounded-2xl border-zinc-200/60 p-5 dark:border-zinc-800/60">
                    <div className="max-w-xs space-y-1.5">
                        <Label htmlFor="project-select" className="text-xs font-bold text-zinc-500">
                            Select Active Project
                        </Label>
                        <select
                            id="project-select"
                            className="h-9 w-full rounded-md border bg-card px-2.5 py-1 text-sm font-medium focus:outline-none"
                            value={selectedProjectId}
                            onChange={(e) =>
                                handleProjectChange(
                                    e.target.value
                                        ? Number(e.target.value)
                                        : '',
                                )
                            }
                        >
                            <option value="">-- Choose a Project --</option>
                            {projects.map((p) => (
                                <option key={p.id} value={p.id}>
                                    [{p.key}] {p.name}
                                </option>
                            ))}
                        </select>
                    </div>
                </Card>

                {/* Timelines Mapping Table */}
                {selectedProjectId ? (
                    <Card className="overflow-hidden rounded-2xl border-zinc-200/60 shadow-sm dark:border-zinc-800/60">
                        <div className="overflow-x-auto">
                            <table className="w-full border-collapse text-left text-xs">
                                <thead>
                                    <tr className="border-b border-zinc-100 bg-zinc-50/50 text-zinc-500 dark:border-zinc-800/50 dark:bg-zinc-900/20">
                                        <th className="p-4 font-bold">Timeline Stage</th>
                                        <th className="p-4 font-bold">Proposed TCD</th>
                                        <th className="p-4 font-bold">Revised TCD</th>
                                        <th className="p-4 font-bold">Status</th>
                                        <th className="p-4 font-bold">Delay Reason</th>
                                        <th className="p-4 font-bold">Remarks</th>
                                        <th className="p-4 font-bold text-right">Actions</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-zinc-100 dark:divide-zinc-800/50">
                                    {timelines.map((t) => renderTimelineRow(t))}
                                </tbody>
                            </table>
                        </div>
                    </Card>
                ) : (
                    <div className="flex flex-col items-center justify-center rounded-2xl border-2 border-dashed border-zinc-200 py-12 text-center dark:border-zinc-800">
                        <Milestone className="size-10 text-zinc-300 dark:text-zinc-700" />
                        <h3 className="mt-4 text-sm font-bold text-zinc-900 dark:text-zinc-100">
                            No Project Selected
                        </h3>
                        <p className="mt-1 text-xs text-zinc-500">
                            Please select a project from the dropdown list above to view and update development timelines.
                        </p>
                    </div>
                )}
            </div>
        </>
    );
}
