'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Settings, Trash2, Plus } from 'lucide-react';
import { cn } from '../../../../lib/utils.js';
import { Button } from '../../../../components/ui/button.js';
import { Input } from '../../../../components/ui/input.js';
import { Badge } from '../../../../components/ui/badge.js';
import { EstimateSettings } from '../../../../components/pm/estimate-settings/estimate-settings.js';
import { ProjectMembersPanel } from '../../../../components/features/projects/project-members-panel.js';
import { updatePmProject } from '../../../actions/update-pm-project.js';
import { deletePmProject } from '../../../actions/delete-pm-project.js';
import { createWorkItemState, deleteWorkItemState } from '../../../actions/manage-work-item-states.js';
import { createLabel, deleteLabel } from '../../../actions/manage-labels.js';
import { addProjectMember } from '../../../actions/add-project-member.js';
import { removeProjectMember } from '../../../actions/remove-project-member.js';
import { updateProjectMemberRole } from '../../../actions/update-project-member-role.js';
const STATE_GROUP_COLORS = {
    backlog: 'bg-gray-400',
    unstarted: 'bg-blue-400',
    started: 'bg-yellow-400',
    completed: 'bg-green-400',
    cancelled: 'bg-red-400',
};
export function ProjectSettingsClient({ project, states: initialStates, labels: initialLabels, members: initialMembers = [], className, }) {
    const router = useRouter();
    const [name, setName] = useState(project.name);
    const [description, setDescription] = useState(project.description ?? '');
    const [saving, setSaving] = useState(false);
    const [states, setStates] = useState(initialStates);
    const [labels, setLabels] = useState(initialLabels);
    const [newStateName, setNewStateName] = useState('');
    const [newLabelName, setNewLabelName] = useState('');
    const [newLabelColor, setNewLabelColor] = useState('#6366f1');
    const [deleteConfirm, setDeleteConfirm] = useState('');
    const handleSaveGeneral = useCallback(async () => {
        setSaving(true);
        await updatePmProject(project.id, {
            name: name.trim(),
            description: description.trim() || undefined,
        });
        setSaving(false);
    }, [project.id, name, description]);
    const handleAddState = useCallback(async () => {
        if (!newStateName.trim())
            return;
        const result = await createWorkItemState({
            projectId: project.id,
            name: newStateName.trim(),
            color: '#6366f1',
            stateGroup: 'unstarted',
        });
        if (result.state) {
            setStates((prev) => [...prev, result.state]);
            setNewStateName('');
        }
    }, [project.id, newStateName]);
    const handleDeleteState = useCallback(async (stateId) => {
        const result = await deleteWorkItemState(stateId);
        if (!result.error) {
            setStates((prev) => prev.filter((s) => s.id !== stateId));
        }
    }, []);
    const handleAddLabel = useCallback(async () => {
        if (!newLabelName.trim())
            return;
        const result = await createLabel({
            projectId: project.id,
            name: newLabelName.trim(),
            color: newLabelColor,
        });
        if (result.label) {
            setLabels((prev) => [...prev, result.label]);
            setNewLabelName('');
        }
    }, [project.id, newLabelName, newLabelColor]);
    const handleDeleteLabel = useCallback(async (labelId) => {
        const result = await deleteLabel(labelId);
        if (!result.error) {
            setLabels((prev) => prev.filter((l) => l.id !== labelId));
        }
    }, []);
    const handleDeleteProject = useCallback(async () => {
        if (deleteConfirm !== project.name)
            return;
        const result = await deletePmProject(project.id);
        if (!result.error) {
            router.push('/projects');
        }
    }, [project.id, project.name, deleteConfirm, router]);
    return (_jsxs("div", { "data-testid": "project-settings", className: cn('max-w-2xl space-y-8', className), children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Button, { variant: "ghost", size: "sm", className: "h-7 w-7 p-0", onClick: () => router.push(`/projects/${project.slug}`), "data-testid": "back-to-project", children: _jsx(ArrowLeft, { className: "h-4 w-4" }) }), _jsx(Settings, { className: "text-muted-foreground h-4 w-4" }), _jsx("h1", { className: "text-sm font-bold tracking-tight", children: "Project Settings" }), _jsx(Badge, { variant: "outline", className: "text-[10px]", children: project.identifierPrefix })] }), _jsxs("section", { className: "space-y-3", "data-testid": "general-settings", children: [_jsx("h2", { className: "text-xs font-semibold tracking-wide uppercase", children: "General" }), _jsxs("div", { className: "space-y-2", children: [_jsxs("div", { children: [_jsx("label", { className: "text-muted-foreground mb-1 block text-[10px] font-medium", children: "Project Name" }), _jsx(Input, { value: name, onChange: (e) => setName(e.target.value), className: "h-8 text-xs", "data-testid": "project-name-input" })] }), _jsxs("div", { children: [_jsx("label", { className: "text-muted-foreground mb-1 block text-[10px] font-medium", children: "Description" }), _jsx(Input, { value: description, onChange: (e) => setDescription(e.target.value), placeholder: "Optional description", className: "h-8 text-xs", "data-testid": "project-description-input" })] }), _jsx(Button, { size: "sm", className: "h-7 text-xs", onClick: handleSaveGeneral, disabled: saving || !name.trim(), "data-testid": "save-general-btn", children: saving ? 'Saving...' : 'Save Changes' })] })] }), _jsx("hr", { className: "border-border" }), _jsx("section", { "data-testid": "estimate-settings-section", children: _jsx(EstimateSettings, { projectId: project.id, currentEstimateType: project.estimateType }) }), _jsx("hr", { className: "border-border" }), _jsxs("section", { className: "space-y-3", "data-testid": "states-settings", children: [_jsx("h2", { className: "text-xs font-semibold tracking-wide uppercase", children: "Work Item States" }), _jsx("div", { className: "space-y-1", children: states.map((state) => (_jsxs("div", { className: "group flex items-center gap-2 rounded-sm px-2 py-1 text-xs", "data-testid": `state-${state.id}`, children: [_jsx("span", { className: "h-2.5 w-2.5 shrink-0 rounded-full", style: { backgroundColor: state.color } }), _jsx("span", { className: "flex-1", children: state.name }), _jsx(Badge, { variant: "outline", className: cn('text-[9px]', STATE_GROUP_COLORS[state.stateGroup] ?? 'bg-gray-400'), children: state.stateGroup }), state.isDefault ? (_jsx(Badge, { variant: "secondary", className: "text-[9px]", children: "default" })) : (_jsx(Button, { variant: "ghost", size: "sm", className: "text-destructive hidden h-5 w-5 p-0 group-hover:flex", onClick: () => handleDeleteState(state.id), title: "Delete state", children: _jsx(Trash2, { className: "h-3 w-3" }) }))] }, state.id))) }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Input, { value: newStateName, onChange: (e) => setNewStateName(e.target.value), placeholder: "New state name", className: "h-7 flex-1 text-xs", "data-testid": "new-state-input", onKeyDown: (e) => {
                                    if (e.key === 'Enter')
                                        handleAddState();
                                } }), _jsxs(Button, { variant: "outline", size: "sm", className: "h-7 text-xs", onClick: handleAddState, disabled: !newStateName.trim(), "data-testid": "add-state-btn", children: [_jsx(Plus, { className: "mr-1 h-3 w-3" }), "Add"] })] })] }), _jsx("hr", { className: "border-border" }), _jsxs("section", { className: "space-y-3", "data-testid": "labels-settings", children: [_jsx("h2", { className: "text-xs font-semibold tracking-wide uppercase", children: "Labels" }), labels.length === 0 ? (_jsx("p", { className: "text-muted-foreground text-[10px]", children: "No labels yet" })) : (_jsx("div", { className: "flex flex-wrap gap-1.5", children: labels.map((label) => (_jsxs("div", { className: "group flex items-center gap-1 rounded-full border px-2 py-0.5", "data-testid": `label-${label.id}`, children: [_jsx("span", { className: "h-2 w-2 rounded-full", style: { backgroundColor: label.color } }), _jsx("span", { className: "text-[10px]", children: label.name }), _jsx("button", { type: "button", className: "text-destructive ml-0.5 hidden text-xs group-hover:inline", onClick: () => handleDeleteLabel(label.id), title: "Delete label", children: "\u00D7" })] }, label.id))) })), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("input", { type: "color", value: newLabelColor, onChange: (e) => setNewLabelColor(e.target.value), className: "h-7 w-7 cursor-pointer rounded border-0 p-0", "data-testid": "new-label-color" }), _jsx(Input, { value: newLabelName, onChange: (e) => setNewLabelName(e.target.value), placeholder: "New label name", className: "h-7 flex-1 text-xs", "data-testid": "new-label-input", onKeyDown: (e) => {
                                    if (e.key === 'Enter')
                                        handleAddLabel();
                                } }), _jsxs(Button, { variant: "outline", size: "sm", className: "h-7 text-xs", onClick: handleAddLabel, disabled: !newLabelName.trim(), "data-testid": "add-label-btn", children: [_jsx(Plus, { className: "mr-1 h-3 w-3" }), "Add"] })] })] }), _jsx("hr", { className: "border-border" }), _jsx("section", { "data-testid": "members-settings", children: _jsx(ProjectMembersPanel, { projectId: project.id, members: initialMembers, currentUserId: "", onAddMember: addProjectMember, onRemoveMember: removeProjectMember, onUpdateRole: updateProjectMemberRole }) }), _jsx("hr", { className: "border-border" }), _jsxs("section", { className: "space-y-3", "data-testid": "danger-zone", children: [_jsx("h2", { className: "text-destructive text-xs font-semibold tracking-wide uppercase", children: "Danger Zone" }), _jsxs("div", { className: "border-destructive/20 rounded-md border p-3", children: [_jsx("p", { className: "mb-2 text-xs", children: "Permanently delete this project and all its work items, cycles, modules, and pages." }), _jsxs("p", { className: "text-muted-foreground mb-2 text-[10px]", children: ["Type ", _jsx("strong", { children: project.name }), " to confirm."] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Input, { value: deleteConfirm, onChange: (e) => setDeleteConfirm(e.target.value), placeholder: project.name, className: "h-7 flex-1 text-xs", "data-testid": "delete-confirm-input" }), _jsxs(Button, { variant: "destructive", size: "sm", className: "h-7 text-xs", onClick: handleDeleteProject, disabled: deleteConfirm !== project.name, "data-testid": "delete-project-btn", children: [_jsx(Trash2, { className: "mr-1 h-3 w-3" }), "Delete Project"] })] })] })] })] }));
}
