'use client';

import { cn } from '@/lib/utils';
import { useLanguage } from '@/lib/language-context';
import { useState } from 'react';

// Tooth Surface Types
export type Surface = 'top' | 'bottom' | 'left' | 'right' | 'center';
export type ToothStatus = 'healthy' | 'caries' | 'filled' | 'missing' | 'exodontia' | 'crown' | 'rct' | 'implant'; // rct = root canal treatment

// Data structure for a single tooth's state
export interface ToothState {
    id: number;
    status: ToothStatus;
    surfaces: {
        [key in Surface]: ToothStatus;
    };
    notes?: string;
}

interface ToothProps {
    id: number;
    data: ToothState;
    onSurfaceClick: (id: number, surface: Surface) => void;
    onWholeClick: (id: number) => void;
    selectedStatusLabel: string;
    showLabel?: boolean;
    readonly?: boolean;
}

// Helper to get color for status (for the whole-tooth dot)
const getStatusColor = (status: ToothStatus) => {
    switch (status) {
        case 'caries': return 'bg-red-500 border-red-500';
        case 'filled': return 'bg-blue-500 border-blue-500';
        case 'missing': return 'bg-slate-800 border-slate-800';
        case 'exodontia': return 'bg-red-600 border-red-600';
        case 'crown': return 'bg-yellow-500 border-yellow-500';
        case 'rct': return 'bg-purple-500 border-purple-500';
        case 'implant': return 'bg-emerald-500 border-emerald-500';
        default: return 'bg-white border-slate-300'; // healthy
    }
};

// Helper to get fill for status (for SVG paths)
const getStatusFill = (status: ToothStatus) => {
    switch (status) {
        case 'caries': return 'fill-red-400 hover:fill-red-500';
        case 'filled': return 'fill-blue-400 hover:fill-blue-500';
        case 'crown': return 'fill-yellow-400 hover:fill-yellow-500';
        case 'rct': return 'fill-purple-400 hover:fill-purple-500';
        default: return 'fill-white hover:fill-slate-100'; // healthy or missing surface
    }
};

const Tooth = ({ id, data, onSurfaceClick, onWholeClick, selectedStatusLabel, showLabel = true, readonly = false }: ToothProps) => {
    const isMissing = data.status === 'missing';
    const isExodontia = data.status === 'exodontia';
    const isImplant = data.status === 'implant';
    const isAbsentTooth = isMissing || isExodontia;

    return (
        <div className="flex flex-col items-center gap-1">
            {showLabel && <span className="text-xs font-bold text-slate-500">{id}</span>}
            <div className={cn("relative w-10 h-10 md:w-12 md:h-12 border-2 border-slate-300 rounded-sm overflow-hidden", isAbsentTooth && "opacity-40")}>
                <svg viewBox="0 0 100 100" className={cn("w-full h-full bg-slate-50", !readonly && !isAbsentTooth ? "cursor-pointer" : "cursor-default")}>
                    {/* Top surface */}
                    <path
                        d="M0,0 L100,0 L75,25 L25,25 Z"
                        className={cn("transition-colors stroke-slate-300 stroke-1", isAbsentTooth ? "fill-white" : getStatusFill(data.surfaces.top))}
                        onClick={() => !readonly && !isAbsentTooth && onSurfaceClick(id, 'top')}
                    />
                    {/* Bottom surface */}
                    <path
                        d="M0,100 L100,100 L75,75 L25,75 Z"
                        className={cn("transition-colors stroke-slate-300 stroke-1", isAbsentTooth ? "fill-white" : getStatusFill(data.surfaces.bottom))}
                        onClick={() => !readonly && !isAbsentTooth && onSurfaceClick(id, 'bottom')}
                    />
                    {/* Left surface */}
                    <path
                        d="M0,0 L0,100 L25,75 L25,25 Z"
                        className={cn("transition-colors stroke-slate-300 stroke-1", isAbsentTooth ? "fill-white" : getStatusFill(data.surfaces.left))}
                        onClick={() => !readonly && !isAbsentTooth && onSurfaceClick(id, 'left')}
                    />
                    {/* Right surface */}
                    <path
                        d="M100,0 L100,100 L75,75 L75,25 Z"
                        className={cn("transition-colors stroke-slate-300 stroke-1", isAbsentTooth ? "fill-white" : getStatusFill(data.surfaces.right))}
                        onClick={() => !readonly && !isAbsentTooth && onSurfaceClick(id, 'right')}
                    />
                    {/* Center (occlusal) surface */}
                    <rect
                        x="25" y="25" width="50" height="50"
                        className={cn("transition-colors stroke-slate-300 stroke-1", isAbsentTooth ? "fill-white" : getStatusFill(data.surfaces.center))}
                        onClick={() => !readonly && !isAbsentTooth && onSurfaceClick(id, 'center')}
                    />
                    {/* X cross when missing or exodontia */}
                    {isMissing && (
                        <path d="M10,10 L90,90 M90,10 L10,90" stroke="#1e293b" strokeWidth="6" strokeLinecap="round" />
                    )}
                    {isExodontia && (
                        <path d="M10,10 L90,90 M90,10 L10,90" stroke="#dc2626" strokeWidth="6" strokeLinecap="round" />
                    )}
                    {/* Implant marker */}
                    {isImplant && (
                        <>
                            <circle cx="50" cy="38" r="14" fill="none" stroke="#0f766e" strokeWidth="5" />
                            <line x1="50" y1="52" x2="50" y2="82" stroke="#0f766e" strokeWidth="5" strokeLinecap="round" />
                            <line x1="38" y1="60" x2="62" y2="60" stroke="#0f766e" strokeWidth="4" strokeLinecap="round" />
                        </>
                    )}
                </svg>
            </div>
            {/* Whole-tooth status dot — click to toggle whole-tooth status (missing, crown, rct) */}
            <div
                className={cn(
                    "w-3 h-3 rounded-full border-2 transition-colors",
                    getStatusColor(data.status),
                    !readonly ? "cursor-pointer hover:opacity-80" : "cursor-default"
                )}
                onClick={() => !readonly && onWholeClick(id)}
                title={readonly ? data.status : `${selectedStatusLabel}`}
            />
        </div>
    );
};

interface InteractiveOdontogramProps {
    initialData?: ToothState[];
    onChange?: (data: ToothState[]) => void;
    readonly?: boolean;
}

const ADULT_TEETH = [18, 17, 16, 15, 14, 13, 12, 11, 21, 22, 23, 24, 25, 26, 27, 28, 48, 47, 46, 45, 44, 43, 42, 41, 31, 32, 33, 34, 35, 36, 37, 38];
const PRIMARY_TEETH = [56, 55, 54, 53, 52, 51, 61, 62, 63, 64, 65, 66, 86, 85, 84, 83, 82, 81, 71, 72, 73, 74, 75, 76];
const ALL_TEETH = [...ADULT_TEETH, ...PRIMARY_TEETH];

const buildInitialTeeth = (initialData?: ToothState[]): Record<number, ToothState> => {
    const state: Record<number, ToothState> = {};
    ALL_TEETH.forEach(id => {
        state[id] = {
            id,
            status: 'healthy',
            surfaces: { top: 'healthy', bottom: 'healthy', left: 'healthy', right: 'healthy', center: 'healthy' }
        };
    });
    if (initialData) {
        initialData.forEach(t => {
            if (state[t.id]) state[t.id] = t;
        });
    }
    return state;
};

export default function InteractiveOdontogram({ initialData, onChange, readonly = false }: InteractiveOdontogramProps) {
    const { t } = useLanguage();
    const [selectedTool, setSelectedTool] = useState<ToothStatus>('caries');
    const [teeth, setTeeth] = useState<Record<number, ToothState>>(() => buildInitialTeeth(initialData));

    const upperRight = [18, 17, 16, 15, 14, 13, 12, 11];
    const upperLeft = [21, 22, 23, 24, 25, 26, 27, 28];
    const lowerRight = [48, 47, 46, 45, 44, 43, 42, 41];
    const lowerLeft = [31, 32, 33, 34, 35, 36, 37, 38];

    const upperRightPrimary = [ 55, 54, 53, 52, 51];
    const upperLeftPrimary = [61, 62, 63, 64, 65];
    const lowerRightPrimary = [ 85, 84, 83, 82, 81];
    const lowerLeftPrimary = [71, 72, 73, 74, 75];
    const wholeToothStatuses: ToothStatus[] = ['missing', 'exodontia', 'crown', 'rct', 'implant'];

    const handleSurfaceClick = (id: number, surface: Surface) => {
        if (readonly) return;
        // Whole-tooth statuses are applied using the status dot only.
        if (wholeToothStatuses.includes(selectedTool)) return;

        const tooth = teeth[id];
        const newStatus = tooth.surfaces[surface] === selectedTool ? 'healthy' : selectedTool;

        const newState = {
            ...teeth,
            [id]: {
                ...tooth,
                surfaces: { ...tooth.surfaces, [surface]: newStatus }
            }
        };

        setTeeth(newState);
        onChange?.(Object.values(newState));
    };

    const handleWholeClick = (id: number) => {
        if (readonly) return;

        const tooth = teeth[id];
        const newStatus: ToothStatus = tooth.status === selectedTool ? 'healthy' : selectedTool;

        // When marking a whole-tooth condition, clear all surface colors.
        const newSurfaces = wholeToothStatuses.includes(newStatus)
            ? { top: 'healthy' as ToothStatus, bottom: 'healthy' as ToothStatus, left: 'healthy' as ToothStatus, right: 'healthy' as ToothStatus, center: 'healthy' as ToothStatus }
            : tooth.surfaces;

        const newState = {
            ...teeth,
            [id]: { ...tooth, status: newStatus, surfaces: newSurfaces }
        };

        setTeeth(newState);
        onChange?.(Object.values(newState));
    };

    const tools: { id: ToothStatus; label: string; dotColor: string; wholeOnly?: boolean }[] = [
        { id: 'healthy', label: t('patientDetails.healthy'), dotColor: 'bg-white border-slate-400' },
        { id: 'caries', label: t('patientDetails.decay'), dotColor: 'bg-red-500 border-red-500' },
        { id: 'filled', label: t('patientDetails.filled'), dotColor: 'bg-blue-500 border-blue-500' },
        { id: 'missing', label: t('patientDetails.missing'), dotColor: 'bg-slate-800 border-slate-800', wholeOnly: true },
        { id: 'exodontia', label: t('patientDetails.exodontia'), dotColor: 'bg-red-600 border-red-600', wholeOnly: true },
        { id: 'crown', label: t('patientDetails.crown'), dotColor: 'bg-yellow-500 border-yellow-500', wholeOnly: true },
        { id: 'rct', label: t('patientDetails.rootCanal'), dotColor: 'bg-purple-500 border-purple-500', wholeOnly: true },
        { id: 'implant', label: t('patientDetails.implant'), dotColor: 'bg-emerald-500 border-emerald-500', wholeOnly: true },
    ];
    const selectedToolLabel = tools.find(tool => tool.id === selectedTool)?.label || selectedTool;

    return (
        <div className="space-y-6">
            {!readonly && (
                <div className="flex flex-wrap gap-3 justify-center bg-slate-50 p-4 rounded-xl border border-slate-200">
                    {tools.map(tool => (
                        <button
                            key={tool.id}
                            type="button"
                            onClick={() => setSelectedTool(tool.id)}
                            className={cn(
                                "flex items-center gap-2 px-4 py-2 rounded-lg transition-all border text-sm font-medium",
                                selectedTool === tool.id
                                    ? "bg-slate-900 text-white border-slate-900 shadow-md"
                                    : "bg-white text-slate-700 border-slate-200 hover:bg-slate-100"
                            )}
                        >
                            <div className={cn("w-4 h-4 rounded-full border-2", tool.dotColor)} />
                            <span>{tool.label}</span>
                            {tool.wholeOnly && (
                                <span className="text-xs opacity-60">({t('patientDetails.wholeTooth')})</span>
                            )}
                        </button>
                    ))}
                </div>
            )}

            <div className="flex flex-col items-start gap-10 overflow-x-auto pb-4">
                {/* Upper Arch (Adult) */}
                <div className="flex gap-6 justify-center w-max min-w-full">
                    <div className="flex flex-col items-center gap-1">
                        <span className="text-xs text-slate-400 font-semibold mb-1">{t('patientDetails.upperRight')} (Q1)</span>
                        <div className="flex gap-1 md:gap-2 justify-center">
                            {upperRight.map(id => (
                                <Tooth
                                    key={id}
                                    id={id}
                                    data={teeth[id]}
                                    onSurfaceClick={handleSurfaceClick}
                                    onWholeClick={handleWholeClick}
                                    selectedStatusLabel={selectedToolLabel}
                                    readonly={readonly}
                                />
                            ))}
                        </div>
                    </div>
                    <div className="flex flex-col items-center gap-1">
                        <span className="text-xs text-slate-400 font-semibold mb-1">{t('patientDetails.upperLeft')} (Q2)</span>
                        <div className="flex gap-1 md:gap-2 justify-center">
                            {upperLeft.map(id => (
                                <Tooth
                                    key={id}
                                    id={id}
                                    data={teeth[id]}
                                    onSurfaceClick={handleSurfaceClick}
                                    onWholeClick={handleWholeClick}
                                    selectedStatusLabel={selectedToolLabel}
                                    readonly={readonly}
                                />
                            ))}
                        </div>
                    </div>
                </div>

                {/* Upper Arch (Primary) */}
                <div className="flex gap-6 justify-center w-max min-w-full">
                    <div className="flex flex-col items-center gap-1">
                        <div className="flex gap-1 md:gap-2 justify-center">
                            {upperRightPrimary.map(id => (
                                <Tooth
                                    key={id}
                                    id={id}
                                    data={teeth[id]}
                                    onSurfaceClick={handleSurfaceClick}
                                    onWholeClick={handleWholeClick}
                                    selectedStatusLabel={selectedToolLabel}
                                    readonly={readonly}
                                />
                            ))}
                        </div>
                        <div className="flex gap-1 md:gap-2 justify-center">
                            {lowerRightPrimary.map(id => (
                                <Tooth
                                    key={id}
                                    id={id}
                                    data={teeth[id]}
                                    onSurfaceClick={handleSurfaceClick}
                                    onWholeClick={handleWholeClick}
                                    selectedStatusLabel={selectedToolLabel}
                                    readonly={readonly}
                                />
                            ))}
                        </div>
                    </div>
                    <div className="flex flex-col items-center gap-1">
                        <div className="flex gap-1 md:gap-2 justify-center">
                            {upperLeftPrimary.map(id => (
                                <Tooth
                                    key={id}
                                    id={id}
                                    data={teeth[id]}
                                    onSurfaceClick={handleSurfaceClick}
                                    onWholeClick={handleWholeClick}
                                    selectedStatusLabel={selectedToolLabel}
                                    readonly={readonly}
                                />
                            ))}
                        </div>
                        <div className="flex gap-1 md:gap-2 justify-center">
                            {lowerLeftPrimary.map(id => (
                                <Tooth
                                    key={id}
                                    id={id}
                                    data={teeth[id]}
                                    onSurfaceClick={handleSurfaceClick}
                                    onWholeClick={handleWholeClick}
                                    selectedStatusLabel={selectedToolLabel}
                                    readonly={readonly}
                                />
                            ))}
                        </div>
                    </div>
                </div>

                {/* Lower Arch (Adult) */}
                <div className="flex gap-6 justify-center w-max min-w-full">
                    <div className="flex flex-col items-center gap-1">
                        <div className="flex gap-1 md:gap-2 justify-center">
                            {lowerRight.map(id => (
                                <Tooth
                                    key={id}
                                    id={id}
                                    data={teeth[id]}
                                    onSurfaceClick={handleSurfaceClick}
                                    onWholeClick={handleWholeClick}
                                    selectedStatusLabel={selectedToolLabel}
                                    readonly={readonly}
                                />
                            ))}
                        </div>
                        <span className="text-xs text-slate-400 font-semibold mt-1">{t('patientDetails.lowerRight')} (Q4)</span>
                    </div>
                    <div className="flex flex-col items-center gap-1">
                        <div className="flex gap-1 md:gap-2 justify-center">
                            {lowerLeft.map(id => (
                                <Tooth
                                    key={id}
                                    id={id}
                                    data={teeth[id]}
                                    onSurfaceClick={handleSurfaceClick}
                                    onWholeClick={handleWholeClick}
                                    selectedStatusLabel={selectedToolLabel}
                                    readonly={readonly}
                                />
                            ))}
                        </div>
                        <span className="text-xs text-slate-400 font-semibold mt-1">{t('patientDetails.lowerLeft')} (Q3)</span>
                    </div>
                </div>
            </div>

            <div className="text-center text-sm text-muted-foreground">
                {readonly
                    ? t('patientDetails.viewOnlyMode')
                    : wholeToothStatuses.includes(selectedTool)
                        ? t('patientDetails.wholeToothInstruction').replace('{status}', selectedToolLabel)
                        : t('patientDetails.odontogramInstruction')
                }
            </div>
        </div>
    );
}
