'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 { FormTextField, FormSelectField, FormTextareaField } = useFormFields<FollowupFormValues>();

  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
        }
      });
    }
  });

  const mutation = useMutation({
    ...createLeadFollowupMutation,
    onSuccess: () => {
      toast.success('บันทึก follow-up สำเร็จ');
      form.reset();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : 'ไม่สามารถบันทึก follow-up ได้');
    }
  });

  return (
    <div className='space-y-4'>
      <Card>
        <CardHeader>
          <CardTitle>New Follow-up</CardTitle>
        </CardHeader>
        <CardContent>
          <form.AppForm>
            <form.Form id='lead-followup-form' className='grid gap-4 md:grid-cols-2'>
              <FormTextField name='followupDate' label='Follow-up Date' placeholder='YYYY-MM-DD' />
              <FormTextField
                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 />
              <FormTextareaField name='note' label='Note' className='md:col-span-2' />
              <div className='md:col-span-2'>
                <Button type='submit' form='lead-followup-form' isLoading={mutation.isPending}>
                  Save Follow-up
                </Button>
              </div>
            </form.Form>
          </form.AppForm>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>History</CardTitle>
        </CardHeader>
        <CardContent className='space-y-3'>
          {detail.followups.length === 0 ? (
            <div className='text-muted-foreground text-sm'>No follow-up history yet.</div>
          ) : (
            detail.followups.map((followup) => (
              <div key={followup.id} className='border-border rounded-md border p-3'>
                <div className='flex items-center justify-between gap-3'>
                  <div className='font-medium'>
                    {followup.followupStatusLabel ?? followup.followupStatus}
                  </div>
                  <div className='text-muted-foreground text-xs'>{formatDate(followup.followupDate)}</div>
                </div>
                {followup.note ? <div className='mt-2 text-sm'>{followup.note}</div> : null}
                <div className='text-muted-foreground mt-2 text-xs'>
                  {followup.createdByName ?? followup.createdBy}
                </div>
              </div>
            ))
          )}
        </CardContent>
      </Card>
    </div>
  );
}
