'use client';

import { useEffect, useMemo } from 'react';
import Link from 'next/link';
import { useMutation } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { useAppForm, useFormFields } from '@/components/ui/tanstack-form';
import type { LeadDetail, LeadReferenceData, LeadSummary } from '../api/types';
import { assignLeadMutation } from '../api/mutations';

type AssignmentFormValues = {
  salesOwnerId: string;
  assignmentRemark: string | null;
};

function toDefaultValues(
  lead: LeadSummary | LeadDetail,
  referenceData: LeadReferenceData
): AssignmentFormValues {
  return {
    salesOwnerId:
      lead.assignedSalesOwnerId ??
      lead.suggestedSalesOwnerId ??
      referenceData.assignableUsers[0]?.id ??
      '',
    assignmentRemark: lead.assignmentRemark ?? null
  };
}

export function LeadAssignmentDialog({
  lead,
  referenceData,
  open,
  onOpenChange
}: {
  lead: LeadSummary | LeadDetail;
  referenceData: LeadReferenceData;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const defaultValues = useMemo(() => toDefaultValues(lead, referenceData), [lead, referenceData]);
  const { FormSelectField, FormTextareaField } = useFormFields<AssignmentFormValues>();

  const mutation = useMutation({
    ...assignLeadMutation,
    onSuccess: (result) => {
      toast.success(
        result.reusedExistingOpportunity
          ? `มอบหมายสำเร็จและใช้ opportunity เดิม ${result.opportunityCode}`
          : `มอบหมายสำเร็จและสร้าง opportunity ${result.opportunityCode}`
      );
      onOpenChange(false);
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : 'ไม่สามารถมอบหมายลีดได้');
    }
  });

  const form = useAppForm({
    defaultValues,
    onSubmit: async ({ value }) => {
      await mutation.mutateAsync({
        leadId: lead.id,
        values: {
          salesOwnerId: value.salesOwnerId,
          assignmentRemark: value.assignmentRemark || null
        }
      });
    }
  });

  useEffect(() => {
    if (open) {
      form.reset(defaultValues);
    }
  }, [defaultValues, form, open]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Assign Lead to Sales</DialogTitle>
          <DialogDescription>
            มอบหมายลีดให้ฝ่ายขายและสร้าง opportunity workspace แยกจาก lead workspace
          </DialogDescription>
        </DialogHeader>

        <form.AppForm>
          <form.Form id='lead-assignment-form' className='space-y-4'>
            <FormSelectField
              name='salesOwnerId'
              label='Sales Owner'
              options={referenceData.assignableUsers.map((user) => ({
                value: user.id,
                label: user.name
              }))}
            />
            <FormTextareaField
              name='assignmentRemark'
              label='Assignment Remark'
              placeholder='Optional handoff context for sales'
            />
          </form.Form>
        </form.AppForm>

        {lead.suggestedSalesOwnerName ? (
          <div className='text-muted-foreground text-sm'>
            Suggested customer owner: {lead.suggestedSalesOwnerName}
          </div>
        ) : null}

        <DialogFooter>
          <Button variant='outline' onClick={() => onOpenChange(false)} disabled={mutation.isPending}>
            Cancel
          </Button>
          <Button type='submit' form='lead-assignment-form' isLoading={mutation.isPending}>
            Assign
          </Button>
        </DialogFooter>

        {'linkedOpportunities' in lead && lead.linkedOpportunities.length > 0 ? (
          <div className='border-border rounded-md border p-3 text-sm'>
            <div className='mb-2 font-medium'>Linked opportunities</div>
            <div className='space-y-1'>
              {lead.linkedOpportunities.map((opportunity) => (
                <Link
                  key={opportunity.id}
                  href={`/dashboard/crm/opportunities/${opportunity.id}`}
                  className='block hover:underline'
                >
                  {opportunity.code} - {opportunity.title}
                </Link>
              ))}
            </div>
          </div>
        ) : null}
      </DialogContent>
    </Dialog>
  );
}

