'use client';

import { useEffect, useState } from 'react';
import { Check, ClipboardCheck, X } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import type { TicketDetail } from '@/types';

import { useReviewRepairMutation } from '../../../hooks/useTicketQueries';
import { TicketActionCard } from './TicketActionCard';

export function ReviewRepairAction({ ticket }: { ticket: TicketDetail }) {
  const [reviewComment, setReviewComment] = useState('');
  const reviewRepairMutation = useReviewRepairMutation(ticket.id);

  useEffect(() => {
    setReviewComment(ticket.reviewer?.review_comment ?? '');
  }, [ticket]);

  return (
    <TicketActionCard icon={ClipboardCheck} title="Review Repair">
      <div className="space-y-4">
        <div className="space-y-2">
          <Label>Comment</Label>
          <Textarea
            value={reviewComment}
            onChange={(event) => setReviewComment(event.target.value)}
            placeholder="Repair verified"
          />
        </div>
        <div className="grid grid-cols-2 gap-2">
          <Button
            disabled={!reviewComment || reviewRepairMutation.isPending}
            onClick={() =>
              reviewRepairMutation.mutate({
                defect_class: ticket.defect_class,
                action: 'approve',
                comment: reviewComment,
              })
            }
          >
            <Check />
            Approve
          </Button>
          <Button
            variant="destructive"
            disabled={!reviewComment || reviewRepairMutation.isPending}
            onClick={() =>
              reviewRepairMutation.mutate({
                defect_class: ticket.defect_class,
                action: 'reject',
                comment: reviewComment,
              })
            }
          >
            <X />
            Reject
          </Button>
        </div>
      </div>
    </TicketActionCard>
  );
}
