'use client';

import { useMutation } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { useAppForm, useFormFields } from '@/components/ui/tanstack-form';
import { formatDate } from '@/lib/date-format';
import type { LeadDetailResponse } from '../api/types';
import { createLeadFollowupMutation } from '../api/mutations';

type FollowupFormValues = {
  followupDate: string;
  followupStatus: string;
  note: string | null;
  nextFollowupDate: string | null;
};

export function LeadFollowupPanel({
  leadId,
  detail
}: {
  leadId: string;
  detail: LeadDetailResponse;
}) {
  const { FormDatePickerField, FormSelectField, FormTextareaField } =
    useFormFields<FollowupFormValues>();

  const mutation = useMutation({
    ...createLeadFollowupMutation,
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : 'Unable to save lead follow-up');
    }
  });

  const form = useAppForm({
    defaultValues: {
      followupDate: '',
      followupStatus: detail.referenceData.followupStatuses[0]?.id ?? '',
      note: null,
      nextFollowupDate: null
    },
    onSubmit: async ({ value }) => {
      await mutation.mutateAsync({
        leadId,
        values: {
          followupDate: value.followupDate,
          followupStatus: value.followupStatus,
          note: value.note || null,
          nextFollowupDate: value.nextFollowupDate || null
        }
      });
      toast.success('Saved lead follow-up successfully');
      form.reset();
    }
  });

  return (
    <Card>
      <CardHeader>
        <CardTitle>Follow-ups</CardTitle>
      </CardHeader>
      <CardContent className='flex flex-col gap-6'>
        <form.AppForm>
          <form.Form id='lead-followup-form' className='grid gap-4 md:grid-cols-2'>
            <FormDatePickerField
              name='followupDate'
              label='Follow-up Date'
              required
              placeholder='YYYY-MM-DD'
            />
            <FormDatePickerField
              name='nextFollowupDate'
              label='Next Follow-up Date'
              placeholder='YYYY-MM-DD'
            />
            <FormSelectField
              name='followupStatus'
              label='Follow-up Status'
              options={detail.referenceData.followupStatuses.map((item) => ({
                value: item.id,
                label: item.label
              }))}
            />
            <div className='md:col-span-2'>
              <FormTextareaField
                name='note'
                label='Note'
                size='md'
                placeholder='Summarize the latest customer conversation and next step.'
              />
            </div>
          </form.Form>
        </form.AppForm>

        <div className='flex justify-end'>
          <Button type='submit' form='lead-followup-form' isLoading={mutation.isPending}>
            Save Follow-up
          </Button>
        </div>

        <div className='flex flex-col gap-3'>
          {detail.followups.length === 0 ? (
            <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center text-sm'>
              No follow-ups yet.
            </div>
          ) : (
            detail.followups.map((followup) => (
              <div key={followup.id} className='rounded-lg border p-4'>
                <div className='font-medium'>{followup.followupStatusLabel ?? followup.followupStatus}</div>
                <div className='text-muted-foreground mt-1 text-xs'>
                  {formatDate(followup.followupDate)}
                </div>
                <div className='mt-2 text-sm'>{followup.note || '-'}</div>
                {followup.nextFollowupDate ? (
                  <div className='text-muted-foreground mt-2 text-xs'>
                    Next: {formatDate(followup.nextFollowupDate)}
                  </div>
                ) : null}
              </div>
            ))
          )}
        </div>
      </CardContent>
    </Card>
  );
}
