'use client';

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

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

  return (
    <div className='space-y-4'>
      <SectionCard
        title={data.opportunity.title}
        description={`${data.opportunity.code} / ${data.branch.name}`}
        action={
          <Button isLoading={mutation.isPending} onClick={() => mutation.mutate(data.opportunity.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.opportunity.chancePercent}%` },
            { label: 'Potential', value: formatCurrency(data.opportunity.expectedValue) },
            { label: 'Project Location', value: data.opportunity.projectLocation },
            { label: 'Competitor', value: data.opportunity.competitor },
            { label: 'Salesman', value: data.salesman.name },
            { label: 'Requirement', value: data.opportunity.requirementSummary }
          ]}
        />
      </SectionCard>

      <SectionCard title='Timeline / Activity'>
        <TimelineList
          items={data.opportunity.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>
  );
}

