import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { api } from '@/lib/api';
import { cn } from '@/lib/utils';
import {
    CheckCircle,
    Flag,
    MessageSquare,
    ShieldAlert,
    XCircle,
} from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import type { ReviewStatus } from './StatusBadge';

type NoteType =
    | 'note'
    | 'reviewed'
    | 'escalated'
    | 'resolved'
    | 'false_positive';

interface NoteTypeOption {
    value: NoteType;
    label: string;
    description: string;
    icon: React.ComponentType<{ className?: string }>;
    cls: string;
}

const NOTE_TYPES: NoteTypeOption[] = [
    {
        value: 'note',
        label: 'Add Note',
        description: 'Document your investigation',
        icon: MessageSquare,
        cls: 'border-border text-foreground hover:border-primary/50 data-[active=true]:border-primary data-[active=true]:bg-primary/5',
    },
    {
        value: 'reviewed',
        label: 'Mark Reviewed',
        description: 'Confirm this was inspected',
        icon: CheckCircle,
        cls: 'border-border text-foreground hover:border-green-500/50 data-[active=true]:border-green-500 data-[active=true]:bg-green-500/5 data-[active=true]:text-green-700 dark:data-[active=true]:text-green-400',
    },
    {
        value: 'escalated',
        label: 'Escalate',
        description: 'Flag as requiring urgent action',
        icon: ShieldAlert,
        cls: 'border-border text-foreground hover:border-red-500/50 data-[active=true]:border-red-500 data-[active=true]:bg-red-500/5 data-[active=true]:text-red-700 dark:data-[active=true]:text-red-400',
    },
    {
        value: 'resolved',
        label: 'Resolved',
        description: 'Issue has been addressed',
        icon: Flag,
        cls: 'border-border text-foreground hover:border-blue-500/50 data-[active=true]:border-blue-500 data-[active=true]:bg-blue-500/5 data-[active=true]:text-blue-700 dark:data-[active=true]:text-blue-400',
    },
    {
        value: 'false_positive',
        label: 'False Positive',
        description: 'Dismiss as a non-issue',
        icon: XCircle,
        cls: 'border-border text-foreground hover:border-muted-foreground/30 data-[active=true]:border-muted-foreground/50 data-[active=true]:bg-muted',
    },
];

interface Props {
    logId: string;
    onSuccess: (result: {
        note: Note;
        review_status: ReviewStatus;
        reviewed_at: string | null;
        reviewed_by_name: string | null;
    }) => void;
    compact?: boolean;
}

export interface Note {
    id: string;
    type: NoteType;
    body: string | null;
    admin_name: string;
    created_at: string;
}

export default function NoteForm({ logId, onSuccess, compact = false }: Props) {
    const [type, setType] = useState<NoteType>('note');
    const [body, setBody] = useState('');
    const [submitting, setSubmitting] = useState(false);

    const selectedOption = NOTE_TYPES.find((o) => o.value === type)!;
    const needsBody = type === 'note';

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (needsBody && !body.trim()) {
            toast.error('Please enter a note.');
            return;
        }
        setSubmitting(true);
        try {
            const result = await api.post<{
                note: Note;
                review_status: ReviewStatus;
                reviewed_at: string | null;
                reviewed_by_name: string | null;
            }>(`/admin/api/audit/${logId}/notes`, {
                type,
                body: body.trim() || null,
            });
            toast.success('Response saved.');
            setBody('');
            setType('note');
            onSuccess(result);
        } catch {
            toast.error('Failed to save. Please try again.');
        } finally {
            setSubmitting(false);
        }
    };

    return (
        <form onSubmit={handleSubmit} className="space-y-3">
            <div
                className={cn(
                    'grid gap-1.5',
                    compact ? 'grid-cols-3' : 'grid-cols-5',
                )}
            >
                {NOTE_TYPES.map((opt) => {
                    const Icon = opt.icon;
                    return (
                        <button
                            key={opt.value}
                            type="button"
                            data-active={type === opt.value}
                            onClick={() => setType(opt.value)}
                            className={cn(
                                'flex flex-col items-center gap-1 rounded-lg border px-2 py-2 text-center transition-all',
                                'focus:ring-primary/30 focus:ring-2 focus:outline-none',
                                opt.cls,
                            )}
                        >
                            <Icon className="h-4 w-4" />
                            <span className="text-[10px] leading-tight font-semibold">
                                {opt.label}
                            </span>
                        </button>
                    );
                })}
            </div>

            {!compact && (
                <p className="text-muted-foreground text-[11px]">
                    {selectedOption.description}
                </p>
            )}

            <Textarea
                value={body}
                onChange={(e) => setBody(e.target.value)}
                placeholder={
                    needsBody
                        ? 'Write your investigation note…'
                        : 'Optional context (recommended)…'
                }
                rows={compact ? 2 : 3}
                className="resize-none text-sm"
            />

            <Button
                type="submit"
                disabled={submitting}
                size="sm"
                className="w-full"
            >
                {submitting ? 'Saving…' : selectedOption.label}
            </Button>
        </form>
    );
}
