import { useForm } from '@inertiajs/react';
import { Folder } from 'lucide-react';
import React from 'react';

import { update as projectUpdate } from '@/actions/App/Domains/Project/Http/Controllers/ProjectController';

import { Button } from '@/components/ui/button';
import { DateTimePicker } from '@/components/ui/datetime-picker';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import type { ProjectEditableData } from '@/types/project';

interface EditProjectDialogProps {
    project: ProjectEditableData | null;
    open: boolean;
    onOpenChange: (open: boolean) => void;
    hasIncompleteTasks?: boolean;
    hasStartedTasks?: boolean;
}

export function EditProjectDialog({
    project,
    open,
    onOpenChange,
    hasIncompleteTasks,
    hasStartedTasks,
}: EditProjectDialogProps) {
    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-125 [&>button:last-child]:hidden">
                {project && (
                    <EditProjectForm
                        key={project.id}
                        project={project}
                        onClose={() => onOpenChange(false)}
                        hasIncompleteTasks={hasIncompleteTasks}
                        hasStartedTasks={hasStartedTasks}
                    />
                )}
            </DialogContent>
        </Dialog>
    );
}

function EditProjectForm({
    project,
    onClose,
    hasIncompleteTasks,
    hasStartedTasks,
}: {
    project: ProjectEditableData;
    onClose: () => void;
    hasIncompleteTasks?: boolean;
    hasStartedTasks?: boolean;
}) {
    const mappedInitialStatus = (() => {
        const status = (project.progressStatus || '').toUpperCase();

        if (status === 'COMPLETED') {
            return 'DONE';
        }

        return status;
    })();

    const { data, setData, put, processing, errors } = useForm({
        projectName: project.projectName,
        description: project.description || '',
        deadline: project.deadline ?? '',
        progressStatus: mappedInitialStatus,
    });

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

        put(projectUpdate({ project: project.id }).url, {
            onSuccess: () => {
                onClose();
            },
        });
    };

    return (
        <>
            <DialogHeader>
                <DialogTitle className="flex items-center gap-2">
                    <Folder className="h-5 w-5" />
                    Edit Project
                </DialogTitle>
                <DialogDescription>
                    Update the project details and progress information.
                </DialogDescription>
            </DialogHeader>

            <form onSubmit={handleSubmit} className="space-y-4 py-4">
                <div className="space-y-2">
                    <Label htmlFor="edit-projectName">Project Name</Label>
                    <Input
                        id="edit-projectName"
                        value={data.projectName}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                            setData('projectName', e.target.value)
                        }
                        placeholder="e.g. Design System 2.0"
                        required
                    />
                    {errors.projectName && (
                        <p className="text-xs text-destructive">
                            {errors.projectName}
                        </p>
                    )}
                </div>

                <div className="space-y-2">
                    <Label htmlFor="edit-description">Description</Label>
                    <Textarea
                        id="edit-description"
                        value={data.description}
                        onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) =>
                            setData('description', e.target.value)
                        }
                        placeholder="Briefly describe what this project is about..."
                        rows={3}
                    />
                    {errors.description && (
                        <p className="text-xs text-destructive">
                            {errors.description}
                        </p>
                    )}
                </div>

                <div className="space-y-2">
                    <Label htmlFor="edit-deadline">Deadline</Label>
                    <DateTimePicker
                        value={data.deadline}
                        onChange={(val) => setData('deadline', val)}
                        placeholder="Pilih tanggal & waktu deadline"
                        ariaLabelledBy="edit-deadline"
                    />
                    {errors.deadline && (
                        <p className="text-xs text-destructive">
                            {errors.deadline}
                        </p>
                    )}
                </div>

                <div className="space-y-2">
                    <Label htmlFor="edit-status">Status</Label>
                    <Select
                        value={data.progressStatus}
                        onValueChange={(val) => setData('progressStatus', val)}
                    >
                        <SelectTrigger id="edit-status">
                            <SelectValue placeholder="Select status" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem
                                value="DRAFT"
                                disabled={hasStartedTasks}
                            >
                                Draft
                            </SelectItem>
                            <SelectItem value="TODO" disabled={hasStartedTasks}>
                                To Do
                            </SelectItem>
                            <SelectItem value="IN_PROGRESS">
                                In Progress
                            </SelectItem>
                            <SelectItem
                                value="DONE"
                                disabled={hasIncompleteTasks}
                            >
                                Done
                            </SelectItem>
                        </SelectContent>
                    </Select>
                    {errors.progressStatus && (
                        <p className="text-xs text-destructive">
                            {errors.progressStatus}
                        </p>
                    )}
                </div>

                <DialogFooter className="pt-4">
                    <Button type="button" variant="outline" onClick={onClose}>
                        Cancel
                    </Button>
                    <Button type="submit" disabled={processing}>
                        {processing ? 'Saving...' : 'Save Changes'}
                    </Button>
                </DialogFooter>
            </form>
        </>
    );
}
