import { router } from '@inertiajs/react';
import { CheckCircle2, ClipboardCheck, RotateCcw } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';

import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { formatDateTime } from '@/lib/utils';
import type { Task } from '@/types/task';

interface TaskReviewSectionProps {
    task: Task;
    canReview?: boolean;
}

const firstErrorMessage = (errors: Record<string, string>) =>
    Object.values(errors)[0] || 'Failed to save the task review';

export function TaskReviewSection({
    task,
    canReview = false,
}: TaskReviewSectionProps) {
    const [reason, setReason] = useState('');
    const [processingDecision, setProcessingDecision] = useState<
        'approved' | 'rejected' | null
    >(null);
    const reviews = task.reviews || [];

    const submitReview = (decision: 'approved' | 'rejected') => {
        if (decision === 'rejected' && !reason.trim()) {
            toast.error('A rejection reason is required');

            return;
        }

        router.post(
            `/tasks/${task.code}/reviews`,
            {
                decision,
                reason: decision === 'rejected' ? reason.trim() : null,
            },
            {
                preserveScroll: true,
                onBefore: () => setProcessingDecision(decision),
                onSuccess: () => {
                    setReason('');
                    toast.success(
                        decision === 'approved'
                            ? 'Task approved and marked as done'
                            : 'Task returned for revision',
                    );
                },
                onError: (errors) => toast.error(firstErrorMessage(errors)),
                onFinish: () => setProcessingDecision(null),
            },
        );
    };

    if ((!canReview || task.status !== 'review') && reviews.length === 0) {
        return null;
    }

    return (
        <section className="space-y-3">
            <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                    <ClipboardCheck className="h-4 w-4 text-muted-foreground" />
                    <h4 className="text-sm font-semibold tracking-tight">
                        Review Atasan
                    </h4>
                </div>
                {reviews.length > 0 && (
                    <span className="rounded-full bg-muted px-2 py-0.5 text-[10px] font-bold text-muted-foreground">
                        {reviews.length}
                    </span>
                )}
            </div>

            {canReview && task.status === 'review' && (
                <div className="space-y-3 rounded-lg border bg-muted/20 p-3">
                    <p className="text-xs text-muted-foreground">
                        Periksa bukti penyelesaian sebelum menerima atau
                        mengembalikan task.
                    </p>
                    <Textarea
                        value={reason}
                        onChange={(event) => setReason(event.target.value)}
                        placeholder="Alasan jika task perlu diperbaiki..."
                        className="min-h-20 resize-none bg-background"
                        disabled={processingDecision !== null}
                    />
                    <div className="flex justify-end gap-2">
                        <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            className="h-8 gap-1.5 text-xs"
                            disabled={processingDecision !== null}
                            onClick={() => submitReview('rejected')}
                        >
                            <RotateCcw className="h-3.5 w-3.5" />
                            {processingDecision === 'rejected'
                                ? 'Mengembalikan...'
                                : 'Perlu Perbaikan'}
                        </Button>
                        <Button
                            type="button"
                            size="sm"
                            className="h-8 gap-1.5 text-xs"
                            disabled={processingDecision !== null}
                            onClick={() => submitReview('approved')}
                        >
                            <CheckCircle2 className="h-3.5 w-3.5" />
                            {processingDecision === 'approved'
                                ? 'Menyetujui...'
                                : 'Terima'}
                        </Button>
                    </div>
                </div>
            )}

            {reviews.length > 0 && (
                <div className="space-y-2">
                    {reviews.map((review) => (
                        <div
                            key={review.id}
                            className="rounded-lg border bg-background px-3 py-2"
                        >
                            <div className="flex items-center justify-between gap-3">
                                <span className="text-xs font-semibold">
                                    {review.decision === 'approved'
                                        ? 'Task disetujui'
                                        : 'Perlu perbaikan'}
                                </span>
                                <span className="shrink-0 text-[10px] text-muted-foreground">
                                    {formatDateTime(review.created_at)}
                                </span>
                            </div>
                            <p className="mt-1 text-[11px] text-muted-foreground">
                                Oleh {review.reviewer?.name || 'Atasan'}
                            </p>
                            {review.reason && (
                                <p className="mt-2 text-xs leading-relaxed whitespace-pre-wrap">
                                    {review.reason}
                                </p>
                            )}
                        </div>
                    ))}
                </div>
            )}
        </section>
    );
}
