'use client';

import { useEffect, useMemo } from 'react';
import { useMutation } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Icons } from '@/components/icons';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle
} from '@/components/ui/sheet';
import { useAppForm, useFormFields } from '@/components/ui/tanstack-form';
import { createEnquiryFollowupMutation, updateEnquiryFollowupMutation } from '../api/mutations';
import type {
  EnquiryFollowupMutationPayload,
  EnquiryFollowupRecord,
  EnquiryReferenceData
} from '../api/types';
import { enquiryFollowupSchema, type EnquiryFollowupFormValues } from '../schemas/enquiry.schema';

function toDefaultValues(followup: EnquiryFollowupRecord | undefined): EnquiryFollowupFormValues {
  return {
    followupDate: followup?.followupDate ? followup.followupDate.slice(0, 10) : '',
    followupType: followup?.followupType ?? '',
    contactId: followup?.contactId ?? undefined,
    outcome: followup?.outcome ?? '',
    notes: followup?.notes ?? '',
    nextFollowupDate: followup?.nextFollowupDate ? followup.nextFollowupDate.slice(0, 10) : '',
    nextAction: followup?.nextAction ?? ''
  };
}

export function FollowupFormSheet({
  enquiryId,
  followup,
  open,
  onOpenChange,
  referenceData,
  customerId
}: {
  enquiryId: string;
  followup?: EnquiryFollowupRecord;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  referenceData: EnquiryReferenceData;
  customerId: string;
}) {
  const isEdit = !!followup;
  const defaultValues = useMemo(() => toDefaultValues(followup), [followup]);
  const { FormTextField, FormTextareaField } = useFormFields<EnquiryFollowupFormValues>();
  const contactOptions = referenceData.contacts.filter((item) => item.customerId === customerId);

  const createMutation = useMutation({
    ...createEnquiryFollowupMutation,
    onSuccess: () => {
      toast.success('Follow-up created successfully');
      onOpenChange(false);
    },
    onError: (error) =>
      toast.error(error instanceof Error ? error.message : 'Failed to create follow-up')
  });

  const updateMutation = useMutation({
    ...updateEnquiryFollowupMutation,
    onSuccess: () => {
      toast.success('Follow-up updated successfully');
      onOpenChange(false);
    },
    onError: (error) =>
      toast.error(error instanceof Error ? error.message : 'Failed to update follow-up')
  });

  const form = useAppForm({
    defaultValues,
    validators: {
      onSubmit: enquiryFollowupSchema
    },
    onSubmit: async ({ value }) => {
      const payload: EnquiryFollowupMutationPayload = {
        followupDate: value.followupDate,
        followupType: value.followupType,
        contactId: value.contactId || null,
        outcome: value.outcome,
        notes: value.notes,
        nextFollowupDate: value.nextFollowupDate || null,
        nextAction: value.nextAction
      };

      if (isEdit && followup) {
        await updateMutation.mutateAsync({
          enquiryId,
          followupId: followup.id,
          values: payload
        });
        return;
      }

      await createMutation.mutateAsync({
        enquiryId,
        values: payload
      });
    }
  });

  useEffect(() => {
    if (!open) {
      return;
    }

    form.reset(defaultValues);
  }, [defaultValues, form, open]);

  const isPending = createMutation.isPending || updateMutation.isPending;

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className='flex flex-col sm:max-w-2xl'>
        <SheetHeader>
          <SheetTitle>{isEdit ? 'Edit Follow-up' : 'New Follow-up'}</SheetTitle>
          <SheetDescription>
            Keep the enquiry timeline current with the latest customer interaction and next step.
          </SheetDescription>
        </SheetHeader>

        <div className='flex-1 overflow-auto'>
          <form.AppForm>
            <form.Form id='enquiry-followup-form' className='grid gap-4 md:grid-cols-2'>
              <FormTextField
                name='followupDate'
                label='Follow-up Date'
                required
                placeholder='YYYY-MM-DD'
              />
              <form.AppField
                name='followupType'
                children={(field) => (
                  <field.FieldSet>
                    <field.Field>
                      <field.FieldLabel>Follow-up Type *</field.FieldLabel>
                      <Select
                        value={field.state.value ?? ''}
                        onValueChange={(value) => {
                          field.handleChange(value === '__none__' ? '' : value);
                          field.handleBlur();
                        }}
                      >
                        <SelectTrigger aria-label='Follow-up type'>
                          <SelectValue placeholder='Select follow-up type' />
                        </SelectTrigger>
                        <SelectContent>
                          {referenceData.followupTypes.map((item) => (
                            <SelectItem key={item.id} value={item.id}>
                              {item.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </field.Field>
                    <field.FieldError />
                  </field.FieldSet>
                )}
              />
              <form.AppField
                name='contactId'
                children={(field) => (
                  <field.FieldSet>
                    <field.Field>
                      <field.FieldLabel>Contact</field.FieldLabel>
                      <Select
                        value={field.state.value ?? ''}
                        onValueChange={(value) => {
                          field.handleChange(value);
                          field.handleBlur();
                        }}
                      >
                        <SelectTrigger aria-label='Follow-up contact'>
                          <SelectValue placeholder='Select contact' />
                        </SelectTrigger>
                        <SelectContent>
                          {contactOptions.length ? (
                            contactOptions.map((item) => (
                              <SelectItem key={item.id} value={item.id}>
                                {item.name}
                              </SelectItem>
                            ))
                          ) : (
                            <SelectItem value='__none__'>No contact selected</SelectItem>
                          )}
                        </SelectContent>
                      </Select>
                    </field.Field>
                    <field.FieldError />
                  </field.FieldSet>
                )}
              />
              <FormTextField
                name='nextFollowupDate'
                label='Next Follow-up Date'
                placeholder='YYYY-MM-DD'
              />
              <div className='md:col-span-2'>
                <FormTextField
                  name='nextAction'
                  label='Next Action'
                  placeholder='Prepare revised technical proposal'
                />
              </div>
              <div className='md:col-span-2'>
                <FormTextareaField
                  name='outcome'
                  label='Outcome'
                  placeholder='Customer asked for revised dimensions and a site survey'
                />
              </div>
              <div className='md:col-span-2'>
                <FormTextareaField
                  name='notes'
                  label='Notes'
                  placeholder='Internal notes from the follow-up session'
                />
              </div>
            </form.Form>
          </form.AppForm>
        </div>

        <SheetFooter>
          <Button type='button' variant='outline' onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button type='submit' form='enquiry-followup-form' isLoading={isPending}>
            <Icons.check className='mr-2 h-4 w-4' />
            {isEdit ? 'Update Follow-up' : 'Create Follow-up'}
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  );
}
