import {
    Copy,
    Pencil,
    Trash2,
    PauseCircle,
    PlayCircle,
    XCircle,
} from 'lucide-react';
import { useState } from 'react';
import type { ReactNode } from 'react';

import { ConfirmActionDialog } from '@/components/ConfirmActionDialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';

interface ProjectSettingsProps {
    onEdit?: () => void;
    onDuplicate?: () => void;
    onDelete?: () => void;
    can?: {
        update: boolean;
        delete: boolean;
        duplicate: boolean;
    };
    projectStatus?: string;
    onUpdateStatus?: (status: string) => void;
}

// Dialog konfirmasi status yang sedang terbuka. `null` berarti tidak ada.
type StatusDialog = 'hold' | 'resume' | 'cancel' | null;

// Satu baris pengaturan: judul + deskripsi di kiri, aksi di kanan.
function SettingRow({
    title,
    description,
    titleClassName,
    action,
}: {
    title: string;
    description: string;
    titleClassName?: string;
    action: ReactNode;
}) {
    return (
        <div className="flex items-center justify-between gap-4 px-4 py-3.5">
            <div>
                <div className={titleClassName ?? 'font-medium'}>{title}</div>
                <div className="text-xs text-muted-foreground">
                    {description}
                </div>
            </div>
            {action}
        </div>
    );
}

export function ProjectSettings({
    onEdit,
    onDuplicate,
    onDelete,
    can = { update: true, delete: true, duplicate: true },
    projectStatus = 'draft',
    onUpdateStatus,
}: ProjectSettingsProps) {
    const [statusDialog, setStatusDialog] = useState<StatusDialog>(null);

    const isLocked = ['completed', 'cancelled'].includes(projectStatus);
    const isOnHold = projectStatus === 'on_hold';
    const hasDangerZone = can.update || can.delete;

    const closeDialog = () => setStatusDialog(null);

    return (
        <section className="rounded-xl border bg-background p-6 shadow-xs">
            <h2 className="text-lg font-bold">Project Settings</h2>
            <p className="text-sm text-muted-foreground">
                Configure project general settings and permissions.
            </p>

            <div className="mt-6 divide-y overflow-hidden rounded-lg border">
                <SettingRow
                    title="Project Privacy"
                    description="Control who can see this project."
                    action={<Badge variant="outline">Public</Badge>}
                />

                {can.update && (
                    <SettingRow
                        title="Edit Project"
                        description="Update project name, description, and deadline."
                        action={
                            <Button
                                variant="outline"
                                size="sm"
                                onClick={onEdit}
                            >
                                <Pencil className="mr-2 h-4 w-4" /> Edit
                            </Button>
                        }
                    />
                )}

                {can.duplicate && (
                    <SettingRow
                        title="Duplicate Project"
                        description="Create a new copy of this project and its tasks."
                        action={
                            <Button
                                variant="outline"
                                size="sm"
                                onClick={onDuplicate}
                            >
                                <Copy className="mr-2 h-4 w-4" /> Duplicate
                            </Button>
                        }
                    />
                )}

                {can.update && (
                    <SettingRow
                        title={isOnHold ? 'Resume Project' : 'Put on Hold'}
                        titleClassName="font-medium text-amber-600 dark:text-amber-500"
                        description={
                            isOnHold
                                ? 'Resume the project and change status to In Progress.'
                                : 'Pause the project temporarily.'
                        }
                        action={
                            isOnHold ? (
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => setStatusDialog('resume')}
                                >
                                    <PlayCircle className="mr-2 h-4 w-4" />{' '}
                                    Resume
                                </Button>
                            ) : (
                                <Button
                                    variant="outline"
                                    size="sm"
                                    disabled={isLocked}
                                    onClick={() => setStatusDialog('hold')}
                                >
                                    <PauseCircle className="mr-2 h-4 w-4" /> On
                                    Hold
                                </Button>
                            )
                        }
                    />
                )}
            </div>

            {hasDangerZone && (
                <>
                    <h3 className="mt-6 mb-2 text-xs font-semibold tracking-wide text-muted-foreground uppercase">
                        Danger Zone
                    </h3>
                    <div className="divide-y overflow-hidden rounded-lg border border-destructive/20">
                        {can.update && (
                            <SettingRow
                                title="Cancel Project"
                                titleClassName="font-medium text-rose-600 dark:text-rose-500"
                                description="Cancel the project permanently. This action cannot be undone."
                                action={
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        className="text-rose-600 hover:bg-rose-100 hover:text-rose-700 dark:text-rose-500 dark:hover:bg-rose-500/20"
                                        disabled={isLocked}
                                        onClick={() =>
                                            setStatusDialog('cancel')
                                        }
                                    >
                                        <XCircle className="mr-2 h-4 w-4" />{' '}
                                        Cancel
                                    </Button>
                                }
                            />
                        )}

                        {can.delete && (
                            <SettingRow
                                title="Delete Project"
                                titleClassName="font-medium text-destructive"
                                description="Permanently remove this project and all its data."
                                action={
                                    <Button
                                        variant="destructive"
                                        size="sm"
                                        onClick={onDelete}
                                    >
                                        <Trash2 className="mr-2 h-4 w-4" />{' '}
                                        Delete
                                    </Button>
                                }
                            />
                        )}
                    </div>
                </>
            )}

            <ConfirmActionDialog
                open={statusDialog === 'hold'}
                onOpenChange={(next) => !next && closeDialog()}
                onConfirm={() => {
                    onUpdateStatus?.('on_hold');
                    closeDialog();
                }}
                tone="warning"
                icon={PauseCircle}
                title="Put project on hold?"
                description="The project will be paused temporarily and all activity will be suspended. You can resume it at any time."
                confirmLabel="Put on Hold"
                cancelLabel="Cancel"
            />

            <ConfirmActionDialog
                open={statusDialog === 'resume'}
                onOpenChange={(next) => !next && closeDialog()}
                onConfirm={() => {
                    onUpdateStatus?.('in_progress');
                    closeDialog();
                }}
                tone="neutral"
                icon={PlayCircle}
                title="Resume project?"
                description="The project will be resumed and its status will change to In Progress."
                confirmLabel="Resume"
                cancelLabel="Cancel"
            />

            <ConfirmActionDialog
                open={statusDialog === 'cancel'}
                onOpenChange={(next) => !next && closeDialog()}
                onConfirm={() => {
                    onUpdateStatus?.('cancelled');
                    closeDialog();
                }}
                tone="danger"
                variant="center"
                icon={XCircle}
                title="Cancel this project?"
                description="The project status will change to Cancelled. This action cannot be undone."
                confirmLabel="Yes, Cancel Project"
                cancelLabel="Keep Project"
            />
        </section>
    );
}
