'use client';

import { useMutation, useSuspenseQuery } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { enquiryByIdOptions } from '../api/queries';
import { convertEnquiryMutation } from '../api/mutations';
import { InfoGrid, RelatedQuotationList, SectionCard, TimelineList } from './shared';
import { formatCurrency } from '../utils/format';

export function EnquiryDetailPage({ id }: { id: string }) {
  const { data } = useSuspenseQuery(enquiryByIdOptions(id));
  const baseMutation = convertEnquiryMutation;
  const mutation = useMutation({
    ...baseMutation,
    onSuccess: async (...args) => {
      await baseMutation.onSuccess?.(...args);
      toast.success('สร้าง quotation mock เรียบร้อย');
    }
  });

  return (
    <div className='space-y-4'>
      <SectionCard
        title={data.enquiry.title}
        description={`${data.enquiry.code} / ${data.branch.name}`}
        action={
          <Button isLoading={mutation.isPending} onClick={() => mutation.mutate(data.enquiry.id)}>
            Convert to Quotation
          </Button>
        }
      >
        <InfoGrid
          cols={4}
          items={[
            { label: 'Customer', value: data.customer.name },
            { label: 'Contact', value: data.contact.name },
            { label: 'Chance', value: `${data.enquiry.chancePercent}%` },
            { label: 'Potential', value: formatCurrency(data.enquiry.expectedValue) },
            { label: 'Project Location', value: data.enquiry.projectLocation },
            { label: 'Competitor', value: data.enquiry.competitor },
            { label: 'Salesman', value: data.salesman.name },
            { label: 'Requirement', value: data.enquiry.requirementSummary }
          ]}
        />
      </SectionCard>

      <SectionCard title='Timeline / Activity'>
        <TimelineList
          items={data.enquiry.activities.map((activity) => ({
            id: activity.id,
            title: activity.title,
            detail: activity.detail,
            actorName: activity.actorName,
            timestamp: activity.createdAt
          }))}
        />
      </SectionCard>

      <SectionCard title='Related Quotations'>
        <RelatedQuotationList quotations={data.quotations} />
      </SectionCard>
    </div>
  );
}
