'use client';

import { useMemo, useState } from 'react';
import { useMutation, useSuspenseQuery } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Icons } from '@/components/icons';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { CrmTextarea } from '@/features/crm/components/crm-form-controls';
import { assignCustomerOwnerMutation, clearCustomerOwnerMutation } from '../api/mutations';
import { customerByIdOptions } from '../api/queries';
import type { CustomerReferenceData } from '../api/types';
import { formatDateTime } from '@/lib/format';

export function CustomerOwnerCard({
  customerId,
  referenceData,
  canManage
}: {
  customerId: string;
  referenceData: CustomerReferenceData;
  canManage: boolean;
}) {
  const { data } = useSuspenseQuery(customerByIdOptions(customerId));
  const [open, setOpen] = useState(false);
  const [selectedOwnerUserId, setSelectedOwnerUserId] = useState('');
  const [remark, setRemark] = useState('');
  const customer = data.customer;
  const ownerCandidates = useMemo(
    () =>
      referenceData.crmUsers.filter((user) =>
        ['sales', 'sales_manager', 'crm_admin'].includes(user.businessRole)
      ),
    [referenceData.crmUsers]
  );

  const assignMutation = useMutation({
    ...assignCustomerOwnerMutation,
    onSuccess: () => {
      toast.success('บันทึกเจ้าของลูกค้าเรียบร้อย');
      setOpen(false);
      setRemark('');
    },
    onError: (error) =>
      toast.error(error instanceof Error ? error.message : 'ไม่สามารถบันทึกเจ้าของลูกค้าได้')
  });

  const clearMutation = useMutation({
    ...clearCustomerOwnerMutation,
    onSuccess: () => {
      toast.success('ล้างเจ้าของลูกค้าเรียบร้อย');
    },
    onError: (error) =>
      toast.error(error instanceof Error ? error.message : 'ไม่สามารถล้างเจ้าของลูกค้าได้')
  });

  return (
    <>
      <Card>
        <CardHeader>
          <CardTitle>Customer Owner</CardTitle>
          <CardDescription>ผู้ดูแลความสัมพันธ์หลักของลูกค้ารายนี้</CardDescription>
        </CardHeader>
        <CardContent className='space-y-4'>
          <div className='space-y-1'>
            <div className='text-muted-foreground text-xs'>Owner</div>
            <div className='text-sm font-medium'>{customer.ownerName ?? '-'}</div>
          </div>
          <div className='space-y-1'>
            <div className='text-muted-foreground text-xs'>Assigned At</div>
            <div className='text-sm'>
              {customer.ownerAssignedAt ? formatDateTime(customer.ownerAssignedAt) : '-'}
            </div>
          </div>
          <div className='space-y-1'>
            <div className='text-muted-foreground text-xs'>Assigned By</div>
            <div className='text-sm'>{customer.ownerAssignedByName ?? '-'}</div>
          </div>
          {canManage ? (
            <div className='flex flex-wrap gap-2'>
              <Button
                variant='outline'
                size='sm'
                onClick={() => {
                  setSelectedOwnerUserId(customer.ownerUserId ?? ownerCandidates[0]?.id ?? '');
                  setRemark('');
                  setOpen(true);
                }}
              >
                <Icons.edit className='mr-2 h-4 w-4' />
                {customer.ownerUserId ? 'Change Owner' : 'Assign Owner'}
              </Button>
              <Button
                variant='outline'
                size='sm'
                disabled={!customer.ownerUserId || clearMutation.isPending}
                onClick={() => clearMutation.mutate({ id: customerId })}
              >
                <Icons.trash className='mr-2 h-4 w-4' />
                Clear Owner
              </Button>
            </div>
          ) : null}
          <div className='space-y-3 border-t pt-4'>
            <div className='text-sm font-medium'>Owner History</div>
            {!data.ownerHistory.length ? (
              <div className='text-muted-foreground text-sm'>ยังไม่มีประวัติการเปลี่ยน owner</div>
            ) : (
              data.ownerHistory.slice(0, 5).map((item) => (
                <div key={item.id} className='rounded-lg border p-3 text-sm'>
                  <div>
                    {item.oldOwnerName ?? '-'} {'->'} {item.newOwnerName ?? '-'}
                  </div>
                  <div className='text-muted-foreground text-xs'>
                    {formatDateTime(item.changedAt)} โดย {item.changedByName ?? item.changedBy}
                  </div>
                  {item.remark ? <div className='mt-1 text-xs'>{item.remark}</div> : null}
                </div>
              ))
            )}
          </div>
        </CardContent>
      </Card>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{customer.ownerUserId ? 'Change Owner' : 'Assign Owner'}</DialogTitle>
            <DialogDescription>เลือกผู้รับผิดชอบหลักของลูกค้ารายนี้</DialogDescription>
          </DialogHeader>
          <div className='space-y-4'>
            <Select value={selectedOwnerUserId} onValueChange={setSelectedOwnerUserId}>
              <SelectTrigger aria-label='Customer owner'>
                <SelectValue placeholder='Select owner' />
              </SelectTrigger>
              <SelectContent>
                {ownerCandidates.map((user) => (
                  <SelectItem key={user.id} value={user.id}>
                    {user.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <CrmTextarea
              value={remark}
              onChange={(event) => setRemark(event.target.value)}
              placeholder='Remark'
              size='md'
            />
          </div>
          <DialogFooter>
            <Button variant='outline' onClick={() => setOpen(false)}>
              ยกเลิก
            </Button>
            <Button
              isLoading={assignMutation.isPending}
              disabled={!selectedOwnerUserId}
              onClick={() =>
                assignMutation.mutate({
                  id: customerId,
                  values: { ownerUserId: selectedOwnerUserId, remark }
                })
              }
            >
              <Icons.check className='mr-2 h-4 w-4' />
              Save
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
