'use client';

import { useState } from 'react';
import { useMutation, useSuspenseQuery } from '@tanstack/react-query';
import { toast } from 'sonner';
import { AlertModal } from '@/components/modal/alert-modal';
import { Icons } from '@/components/icons';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { deleteCustomerContactMutation } from '../api/mutations';
import { customerContactsOptions } from '../api/queries';
import { ContactFormSheet } from './contact-form-sheet';

export function CustomerContactsTab({
  customerId,
  canCreate,
  canUpdate,
  canDelete
}: {
  customerId: string;
  canCreate: boolean;
  canUpdate: boolean;
  canDelete: boolean;
}) {
  const { data } = useSuspenseQuery(customerContactsOptions(customerId));
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [open, setOpen] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const selectedContact = data.items.find((contact) => contact.id === selectedId);

  const deleteMutation = useMutation({
    ...deleteCustomerContactMutation,
    onSuccess: () => {
      toast.success('ลบผู้ติดต่อสำเร็จ');
      setDeleteOpen(false);
      setSelectedId(null);
    },
    onError: (error) =>
      toast.error(error instanceof Error ? error.message : 'ไม่สามารถลบผู้ติดต่อได้')
  });

  return (
    <Card>
      <CardHeader className='flex flex-row items-start justify-between gap-4'>
        <div>
          <CardTitle>ผู้ติดต่อ</CardTitle>
          <CardDescription>จัดการรายชื่อบุคคลที่ติดต่อกับลูกค้ารายนี้</CardDescription>
        </div>
        {canCreate ? (
          <Button
            size='sm'
            onClick={() => {
              setSelectedId(null);
              setOpen(true);
            }}
          >
            <Icons.add className='mr-2 h-4 w-4' /> เพิ่มผู้ติดต่อ
          </Button>
        ) : null}
      </CardHeader>
      <CardContent className='space-y-4'>
        {!data.items.length ? (
          <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center text-sm'>
            ยังไม่มีผู้ติดต่อ
          </div>
        ) : (
          data.items.map((contact) => (
            <div
              key={contact.id}
              className='flex flex-col gap-3 rounded-lg border p-4 md:flex-row md:items-start md:justify-between'
            >
              <div className='space-y-1'>
                <div className='flex flex-wrap items-center gap-2'>
                  <span className='font-medium'>{contact.name}</span>
                  {contact.isPrimary ? <Badge>ผู้ติดต่อหลัก</Badge> : null}
                  {!contact.isActive ? <Badge variant='outline'>ปิดใช้งาน</Badge> : null}
                </div>
                <div className='text-muted-foreground text-sm'>
                  {[contact.position, contact.department].filter(Boolean).join(' • ') ||
                    'ยังไม่มีข้อมูลตำแหน่ง'}
                </div>
                <div className='text-muted-foreground text-sm'>
                  {[contact.phone, contact.mobile, contact.email].filter(Boolean).join(' • ') ||
                    'ยังไม่มีช่องทางติดต่อ'}
                </div>
                {contact.notes ? <p className='text-sm'>{contact.notes}</p> : null}
              </div>
              <div className='flex gap-2'>
                <Button
                  variant='outline'
                  size='sm'
                  disabled={!canUpdate}
                  onClick={() => {
                    setSelectedId(contact.id);
                    setOpen(true);
                  }}
                >
                  <Icons.edit className='mr-2 h-4 w-4' /> แก้ไข
                </Button>
                <Button
                  variant='outline'
                  size='sm'
                  disabled={!canDelete}
                  onClick={() => {
                    setSelectedId(contact.id);
                    setDeleteOpen(true);
                  }}
                >
                  <Icons.trash className='mr-2 h-4 w-4' /> ลบ
                </Button>
              </div>
            </div>
          ))
        )}
      </CardContent>

      <ContactFormSheet
        customerId={customerId}
        contact={selectedContact}
        open={open}
        onOpenChange={setOpen}
      />
      <AlertModal
        isOpen={deleteOpen}
        onClose={() => setDeleteOpen(false)}
        onConfirm={() => {
          if (selectedId) {
            deleteMutation.mutate({ customerId, contactId: selectedId });
          }
        }}
        loading={deleteMutation.isPending}
      />
    </Card>
  );
}
