import { Head, router, useForm } from '@inertiajs/react';
import {
    Plus,
    Trash2,
    Edit,
    ChevronDown,
    ChevronRight,
    Milestone,
    CornerDownRight,
    Search,
    FileDown,
    FileUp
} from 'lucide-react';
import { useState, useMemo } from 'react';
import { toast } from 'sonner';
import { store as storeTimeline, update as updateTimeline, destroy as destroyTimeline } from '@/routes/settings/timeline-masters';
import { BulkImportModal } from '@/components/bulk-import-modal';
import { Pagination } from '@/components/pagination';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/app-layout';

interface SubTimeline {
    id: number;
    parent_id: number;
    stage: string;
    responsibility: string | null;
    is_micro: boolean;
    is_major: boolean;
}

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

interface Props {
    timelineMasters: TimelineMaster[];
}

export default function TimelineMastersPage({ timelineMasters }: Props) {
    const [isCreateOpen, setIsCreateOpen] = useState(false);
    const [createParentId, setCreateParentId] = useState<number | null>(null);
    const [editingTimeline, setEditingTimeline] =
        useState<TimelineMaster | null>(null);
    const [expandedTimelines, setExpandedTimelines] = useState<
        Record<number, boolean>
    >({});
    const [searchQuery, setSearchQuery] = useState('');

    // Pagination & Bulk Import/Export State
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [isImportOpen, setIsImportOpen] = useState(false);

    const createForm = useForm({
        stage: '',
        responsibility: '',
        parent_id: '' as string | number,
        is_micro: false,
        is_major: false,
    });

    const editForm = useForm({
        stage: '',
        responsibility: '',
        is_micro: false,
        is_major: false,
    });

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

    const handleCreateClick = (parentId: number | null = null) => {
        setCreateParentId(parentId);
        createForm.setData({
            stage: '',
            responsibility: '',
            parent_id: parentId || '',
            is_micro: parentId !== null,
            is_major: parentId === null,
        });
        setIsCreateOpen(true);
    };

    const handleCreate = (e: React.FormEvent) => {
        e.preventDefault();
        createForm.post(storeTimeline.url(), {
            onSuccess: () => {
                setIsCreateOpen(false);
                createForm.reset();
                toast.success('Timeline Master stage created successfully.');
            },
            onError: (errors) => {
                toast.error(
                    errors.stage || 'Failed to create Timeline Master stage.',
                );
            },
        });
    };

    const handleEditClick = (item: TimelineMaster) => {
        setEditingTimeline(item);
        editForm.setData({
            stage: item.stage,
            responsibility: item.responsibility || '',
            is_micro: item.is_micro,
            is_major: item.is_major,
        });
    };

    const handleUpdate = (e: React.FormEvent) => {
        e.preventDefault();

        if (!editingTimeline) {
            return;
        }

        editForm.put(
            updateTimeline.url(editingTimeline.id),
            {
                onSuccess: () => {
                    setEditingTimeline(null);
                    toast.success(
                        'Timeline Master stage updated successfully.',
                    );
                },
                onError: (errors) => {
                    toast.error(
                        errors.stage ||
                            'Failed to update Timeline Master stage.',
                    );
                },
            },
        );
    };

    const handleDelete = (id: number) => {
        if (
            confirm(
                'Are you sure you want to delete this timeline stage and all its children?',
            )
        ) {
            router.delete(destroyTimeline.url(id), {
                onSuccess: () => {
                    toast.success(
                        'Timeline Master stage deleted successfully.',
                    );
                },
            });
        }
    };

    // Filter timeline tree by search query
    const filteredTimelines = useMemo(() => {
        if (searchQuery.trim() === '') {
            return timelineMasters;
        }

        const query = searchQuery.toLowerCase();

        return timelineMasters
            .map((item) => {
                const children = item.children || [];
                const matchesParent =
                    item.stage.toLowerCase().includes(query) ||
                    (item.responsibility &&
                        item.responsibility.toLowerCase().includes(query));

                const filteredChildren = children.filter(
                    (sub) =>
                        sub.stage.toLowerCase().includes(query) ||
                        (sub.responsibility &&
                            sub.responsibility.toLowerCase().includes(query)),
                );

                if (
                    filteredChildren.length > 0 &&
                    !expandedTimelines[item.id]
                ) {
                    setTimeout(() => {
                        setExpandedTimelines((prev) => ({
                            ...prev,
                            [item.id]: true,
                        }));
                    }, 10);
                }

                if (matchesParent || filteredChildren.length > 0) {
                    return {
                        ...item,
                        children: filteredChildren,
                    } as TimelineMaster;
                }

                return null;
            })
            .filter(Boolean) as TimelineMaster[];
    }, [timelineMasters, searchQuery, expandedTimelines]);

    const paginatedTimelines = useMemo(() => {
        const start = (currentPage - 1) * pageSize;

        return filteredTimelines.slice(start, start + pageSize);
    }, [filteredTimelines, currentPage, pageSize]);

    const handleSearchChange = (val: string) => {
        setSearchQuery(val);
        setCurrentPage(1);
    };

    const handleExportCSV = () => {
        const headers = ['Stage Name', 'Responsibility', 'Parent Stage', 'Is Major', 'Is Micro'];
        const rows: any[] = [];
        
        filteredTimelines.forEach(item => {
            rows.push([
                item.stage,
                item.responsibility ?? '',
                '',
                item.is_major ? '1' : '0',
                item.is_micro ? '1' : '0'
            ]);
            item.children?.forEach(sub => {
                rows.push([
                    sub.stage,
                    sub.responsibility ?? '',
                    item.stage,
                    sub.is_major ? '1' : '0',
                    sub.is_micro ? '1' : '0'
                ]);
            });
        });

        const csvContent = "data:text/csv;charset=utf-8," 
            + [headers.join(','), ...rows.map(e => e.map((val: string) => `"${val.replace(/"/g, '""')}"`).join(','))].join('\n');
        const encodedUri = encodeURI(csvContent);
        const link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "timeline_masters_export.csv");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        toast.success('Timeline Masters exported successfully.');
    };

    return (
        <>
            <Head title="Timeline Masters Stages" />
            <div className="from-zinc-550/20 min-h-screen w-full space-y-8 bg-gradient-to-b via-transparent to-transparent p-6 md:p-10">
                {/* Premium Gradient Header Banner */}
                <div className="from-blue-600 relative flex flex-col items-start justify-between gap-6 overflow-hidden rounded-3xl border border-white/10 bg-gradient-to-r via-indigo-600 to-cyan-500 p-8 text-white shadow-2xl md:flex-row md:items-center md:p-10">
                    <div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(255,255,255,0.15),transparent_50%)]" />
                    <div className="relative max-w-2xl space-y-2">
                        <span className="rounded-full border border-white/20 bg-white/20 px-3 py-1 text-[10px] font-extrabold tracking-widest text-white/90 uppercase backdrop-blur-md">
                            Gantt Milestone Blueprint
                        </span>
                        <h3 className="text-2xl font-extrabold tracking-tight md:text-3xl">
                            Timeline Masters Stages
                        </h3>
                        <p className="text-sm font-medium text-blue-100">
                            Configure standard project milestones, define macro
                            or micro scopes, and designate operational roles to
                            deliverable phases.
                        </p>
                    </div>
                    <div className="flex flex-wrap gap-2.5 shrink-0">
                        <Button
                            variant="outline"
                            onClick={handleExportCSV}
                            className="relative flex items-center gap-2 rounded-xl border border-white/20 bg-white/10 hover:bg-white/20 px-4 py-6 font-bold text-white shadow-lg transition-all duration-300 hover:-translate-y-0.5"
                        >
                            <FileDown className="size-4" /> Export CSV
                        </Button>
                        <Button
                            variant="outline"
                            onClick={() => setIsImportOpen(true)}
                            className="relative flex items-center gap-2 rounded-xl border border-white/20 bg-white/10 hover:bg-white/20 px-4 py-6 font-bold text-white shadow-lg transition-all duration-300 hover:-translate-y-0.5"
                        >
                            <FileUp className="size-4" /> Bulk Import
                        </Button>
                        <Button
                            onClick={() => handleCreateClick(null)}
                            className="relative flex items-center gap-2 rounded-xl border border-white/20 bg-white px-5 py-6 font-bold text-blue-950 shadow-lg transition-all duration-300 hover:-translate-y-0.5 hover:bg-zinc-100 hover:shadow-blue-500/20"
                        >
                            <Plus className="size-4 stroke-[3px]" /> Add Stage Milestone
                        </Button>
                    </div>
                </div>

                {/* Filters and Search Toolbar */}
                <div className="flex flex-col items-center gap-4 rounded-2xl border border-zinc-200/80 bg-white/60 p-5 shadow-sm backdrop-blur-2xl sm:flex-row dark:border-zinc-800/80 dark:bg-zinc-900/60">
                    <div className="relative w-full">
                        <Search className="absolute top-1/2 left-3.5 size-4 -translate-y-1/2 text-zinc-400" />
                        <Input
                            className="h-11 rounded-xl border-zinc-200 bg-white/80 pl-10 text-xs shadow-inner focus-visible:ring-indigo-500/50 dark:border-zinc-800 dark:bg-zinc-955/80"
                            placeholder="Search timeline stages or responsibility roles..."
                            value={searchQuery}
                            onChange={(e) => handleSearchChange(e.target.value)}
                        />
                    </div>
                </div>

                {filteredTimelines.length === 0 ? (
                    <Card className="flex flex-col items-center justify-center rounded-3xl border-2 border-dashed border-zinc-200 bg-white/30 p-16 text-center backdrop-blur-sm dark:border-zinc-800 dark:bg-zinc-950/10">
                        <div className="mb-4 animate-pulse rounded-full border border-blue-100 bg-blue-50 p-4 dark:border-blue-900 dark:bg-blue-950/50">
                            <Milestone className="size-8 text-blue-500" />
                        </div>
                        <p className="text-base font-bold text-zinc-800 dark:text-zinc-200">
                            No matching timeline stages found
                        </p>
                    </Card>
                ) : (
                    <div className="space-y-4">
                        {paginatedTimelines.map((timeline) => {
                            const isExpanded = !!expandedTimelines[timeline.id];
                            const children = timeline.children || [];

                            return (
                                <div
                                    key={timeline.id}
                                    className="overflow-hidden rounded-3xl border border-zinc-200/80 bg-white/60 shadow-xl backdrop-blur-2xl transition-all duration-300 dark:border-zinc-800/80 dark:bg-zinc-900/60"
                                >
                                    {/* Header / Main Item */}
                                    <div className="flex items-center justify-between p-5 transition-colors hover:bg-zinc-50/50 dark:hover:bg-zinc-800/10">
                                        <div className="flex min-w-0 flex-1 items-center gap-4">
                                            {children.length > 0 ? (
                                                <button
                                                    onClick={() =>
                                                        toggleExpand(
                                                            timeline.id,
                                                        )
                                                    }
                                                    className="rounded-lg p-1.5 text-zinc-400 transition-colors hover:bg-zinc-100 hover:text-zinc-700 dark:hover:bg-zinc-800 dark:hover:text-zinc-200"
                                                >
                                                    {isExpanded ? (
                                                        <ChevronDown className="size-4.5" />
                                                    ) : (
                                                        <ChevronRight className="size-4.5" />
                                                    )}
                                                </button>
                                            ) : (
                                                <div className="text-blue-550 flex size-8 shrink-0 items-center justify-center rounded-lg border border-blue-100 bg-blue-50 dark:border-blue-900/50 dark:bg-blue-950/50">
                                                    <Milestone className="size-4" />
                                                </div>
                                            )}
                                            <div className="min-w-0 flex-1">
                                                <div className="flex items-center gap-2">
                                                    <h4 className="truncate text-sm font-extrabold text-zinc-900 dark:text-zinc-100">
                                                        {timeline.stage}
                                                    </h4>
                                                    {timeline.is_major && (
                                                        <span className="rounded-md border border-amber-200/50 bg-amber-50 px-2.5 py-0.5 text-[8px] leading-none font-extrabold tracking-wider text-amber-600 uppercase">
                                                            Major Milestone
                                                        </span>
                                                    )}
                                                </div>
                                                {timeline.responsibility && (
                                                    <p className="dark:text-zinc-455 mt-0.5 truncate text-xs font-medium text-zinc-500">
                                                        Responsible:{' '}
                                                        {
                                                            timeline.responsibility
                                                        }
                                                    </p>
                                                )}
                                            </div>
                                        </div>

                                        {/* Action Buttons */}
                                        <div className="ml-4 flex items-center gap-1.5">
                                            <Button
                                                variant="ghost"
                                                size="sm"
                                                onClick={() =>
                                                    handleCreateClick(
                                                        timeline.id,
                                                    )
                                                }
                                                className="flex h-8 items-center gap-1 rounded-xl border border-indigo-100 bg-white/80 px-3.5 text-xs font-extrabold text-indigo-600 shadow-sm hover:bg-indigo-50/80 dark:border-indigo-950/50 dark:bg-zinc-950/80 dark:text-indigo-400 dark:hover:bg-indigo-950/20"
                                            >
                                                <Plus className="size-3.5 stroke-[3px]" />{' '}
                                                Substage
                                            </Button>
                                            <Button
                                                variant="ghost"
                                                size="icon"
                                                className="size-8 rounded-lg text-zinc-500 hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800"
                                                onClick={() =>
                                                    handleEditClick(timeline)
                                                }
                                            >
                                                <Edit className="size-3.5" />
                                            </Button>
                                            <Button
                                                variant="ghost"
                                                size="icon"
                                                className="size-8 rounded-lg text-red-500 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-950/20"
                                                onClick={() =>
                                                    handleDelete(timeline.id)
                                                }
                                            >
                                                <Trash2 className="size-3.5" />
                                            </Button>
                                        </div>
                                    </div>

                                    {/* Children Substages */}
                                    {isExpanded && children.length > 0 && (
                                        <div className="border-zinc-150/50 divide-y divide-zinc-100 border-t bg-zinc-50/20 py-1 pr-5 pl-8 dark:divide-zinc-800/50 dark:border-zinc-800/80 dark:bg-zinc-900/10">
                                            {children.map((substage) => (
                                                <div
                                                    key={substage.id}
                                                    className="flex items-center justify-between rounded-xl px-3 py-4 transition-colors hover:bg-zinc-50/80"
                                                >
                                                    <div className="flex min-w-0 flex-1 items-center gap-2.5">
                                                        <CornerDownRight className="size-4 shrink-0 text-zinc-400" />
                                                        <div className="min-w-0 flex-1">
                                                            <div className="flex items-center gap-2">
                                                                <h5 className="truncate text-xs font-extrabold text-zinc-800 dark:text-zinc-200">
                                                                    {
                                                                        substage.stage
                                                                    }
                                                                </h5>
                                                                {substage.is_micro && (
                                                                    <span className="rounded-md border border-blue-200/50 bg-blue-50 px-2 py-0.5 text-[8px] leading-none font-extrabold tracking-wider text-blue-600 uppercase">
                                                                        Micro
                                                                        Stage
                                                                    </span>
                                                                )}
                                                            </div>
                                                            {substage.responsibility && (
                                                                <p className="dark:text-zinc-550 mt-0.5 truncate text-[11px] font-medium text-zinc-500">
                                                                    Responsible:{' '}
                                                                    {
                                                                        substage.responsibility
                                                                    }
                                                                </p>
                                                            )}
                                                        </div>
                                                    </div>

                                                    <div className="ml-4 flex items-center gap-1">
                                                        <Button
                                                            variant="ghost"
                                                            size="icon"
                                                            className="size-8 rounded-lg text-zinc-500 hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800"
                                                            onClick={() =>
                                                                handleEditClick(
                                                                    substage,
                                                                )
                                                            }
                                                        >
                                                            <Edit className="size-3.5" />
                                                        </Button>
                                                        <Button
                                                            variant="ghost"
                                                            size="icon"
                                                            className="size-8 rounded-lg text-red-500 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-950/20"
                                                            onClick={() =>
                                                                handleDelete(
                                                                    substage.id,
                                                                )
                                                            }
                                                        >
                                                            <Trash2 className="size-3.5" />
                                                        </Button>
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            );
                        })}
                        <Pagination
                            currentPage={currentPage}
                            pageSize={pageSize}
                            totalItems={filteredTimelines.length}
                            onPageChange={setCurrentPage}
                            onPageSizeChange={setPageSize}
                        />
                    </div>
                )}

                {/* Create Dialog */}
                <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
                    <DialogContent className="max-w-sm rounded-2xl">
                        <DialogHeader>
                            <DialogTitle>
                                {createParentId
                                    ? 'Add Substage'
                                    : 'Add Stage Milestone'}
                            </DialogTitle>
                            <DialogDescription>
                                Define a new{' '}
                                {createParentId
                                    ? 'child phase'
                                    : 'primary delivery phase'}
                                .
                            </DialogDescription>
                        </DialogHeader>
                        <form
                            onSubmit={handleCreate}
                            className="space-y-4 pt-2"
                        >
                            <div className="space-y-1">
                                <Label htmlFor="create-stage">
                                    Stage Title
                                </Label>
                                <Input
                                    id="create-stage"
                                    value={createForm.data.stage}
                                    onChange={(e) =>
                                        createForm.setData(
                                            'stage',
                                            e.target.value,
                                        )
                                    }
                                    placeholder="e.g. Design Prototype"
                                    required
                                />
                            </div>
                            <div className="space-y-1">
                                <Label htmlFor="create-responsibility">
                                    Responsibility Role
                                </Label>
                                <Input
                                    id="create-responsibility"
                                    value={createForm.data.responsibility}
                                    onChange={(e) =>
                                        createForm.setData(
                                            'responsibility',
                                            e.target.value,
                                        )
                                    }
                                    placeholder="e.g. UI/UX Lead developer"
                                />
                            </div>
                            <div className="flex items-center space-x-6 pt-2">
                                <div className="flex items-center space-x-2">
                                    <Checkbox
                                        id="create-micro"
                                        checked={createForm.data.is_micro}
                                        onCheckedChange={(checked) =>
                                            createForm.setData(
                                                'is_micro',
                                                checked === true,
                                            )
                                        }
                                    />
                                    <Label
                                        htmlFor="create-micro"
                                        className="text-xs"
                                    >
                                        Micro Stage
                                    </Label>
                                </div>
                                <div className="flex items-center space-x-2">
                                    <Checkbox
                                        id="create-major"
                                        checked={createForm.data.is_major}
                                        onCheckedChange={(checked) =>
                                            createForm.setData(
                                                'is_major',
                                                checked === true,
                                            )
                                        }
                                    />
                                    <Label
                                        htmlFor="create-major"
                                        className="text-xs"
                                    >
                                        Major Milestone
                                    </Label>
                                </div>
                            </div>
                            <DialogFooter className="pt-2">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => setIsCreateOpen(false)}
                                    className="rounded-xl"
                                >
                                    Cancel
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={createForm.processing}
                                    className="rounded-xl"
                                >
                                    Create
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

                {/* Edit Dialog */}
                <Dialog
                    open={!!editingTimeline}
                    onOpenChange={(open) => !open && setEditingTimeline(null)}
                >
                    <DialogContent className="max-w-sm rounded-2xl">
                        <DialogHeader>
                            <DialogTitle>Edit Timeline Master</DialogTitle>
                            <DialogDescription>
                                Update stage properties and delivery details.
                            </DialogDescription>
                        </DialogHeader>
                        <form
                            onSubmit={handleUpdate}
                            className="space-y-4 pt-2"
                        >
                            <div className="space-y-1">
                                <Label htmlFor="edit-stage">Stage Title</Label>
                                <Input
                                    id="edit-stage"
                                    value={editForm.data.stage}
                                    onChange={(e) =>
                                        editForm.setData(
                                            'stage',
                                            e.target.value,
                                        )
                                    }
                                    required
                                />
                            </div>
                            <div className="space-y-1">
                                <Label htmlFor="edit-responsibility">
                                    Responsibility Role
                                </Label>
                                <Input
                                    id="edit-responsibility"
                                    value={editForm.data.responsibility}
                                    onChange={(e) =>
                                        editForm.setData(
                                            'responsibility',
                                            e.target.value,
                                        )
                                    }
                                />
                            </div>
                            <div className="flex items-center space-x-6 pt-2">
                                <div className="flex items-center space-x-2">
                                    <Checkbox
                                        id="edit-micro"
                                        checked={editForm.data.is_micro}
                                        onCheckedChange={(checked) =>
                                            editForm.setData(
                                                'is_micro',
                                                checked === true,
                                            )
                                        }
                                    />
                                    <Label
                                        htmlFor="edit-micro"
                                        className="text-xs"
                                    >
                                        Micro Stage
                                    </Label>
                                </div>
                                <div className="flex items-center space-x-2">
                                    <Checkbox
                                        id="edit-major"
                                        checked={editForm.data.is_major}
                                        onCheckedChange={(checked) =>
                                            editForm.setData(
                                                'is_major',
                                                checked === true,
                                            )
                                        }
                                    />
                                    <Label
                                        htmlFor="edit-major"
                                        className="text-xs"
                                    >
                                        Major Milestone
                                    </Label>
                                </div>
                            </div>
                            <DialogFooter className="pt-2">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => setEditingTimeline(null)}
                                    className="rounded-xl"
                                >
                                    Cancel
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={editForm.processing}
                                    className="rounded-xl"
                                >
                                    Save Changes
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

                {/* Bulk Import Modal */}
                <BulkImportModal
                    isOpen={isImportOpen}
                    onClose={() => setIsImportOpen(false)}
                    importUrl="/settings/timeline-masters/bulk-import"
                    sampleHeaders={['stage', 'responsibility', 'is_major', 'is_micro', 'parent_stage']}
                    sampleRows={[
                        ['Kickoff Phase', 'Project Manager', '1', '0', ''],
                        ['Requirements Signoff', 'Business Analyst', '0', '1', 'Kickoff Phase'],
                        ['Cloud Provisioning', 'DevOps Lead', '0', '1', '']
                    ]}
                    title="Import Timeline Milestones"
                />
            </div>
        </>
    );
}

TimelineMastersPage.layout = (page: React.ReactNode) => (
    <AppLayout>{page}</AppLayout>
);
