'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 { createOpportunityFollowupMutation, updateOpportunityFollowupMutation } from '../api/mutations';
import type {
  OpportunityFollowupMutationPayload,
  OpportunityFollowupRecord,
  OpportunityReferenceData
} from '../api/types';
import { opportunityFollowupSchema, type OpportunityFollowupFormValues } from '../schemas/opportunity.schema';

function toDefaultValues(followup: OpportunityFollowupRecord | undefined): OpportunityFollowupFormValues {
  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({
  opportunityId,
  followup,
  open,
  onOpenChange,
  referenceData,
  customerId
}: {
  opportunityId: string;
  followup?: OpportunityFollowupRecord;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  referenceData: OpportunityReferenceData;
  customerId: string;
}) {
  const isEdit = !!followup;
  const defaultValues = useMemo(() => toDefaultValues(followup), [followup]);
  const { FormTextField, FormTextareaField, FormDatePickerField } =
    useFormFields<OpportunityFollowupFormValues>();
  const contactOptions = referenceData.contacts.filter((item) => item.customerId === customerId);

  const createMutation = useMutation({
    ...createOpportunityFollowupMutation,
    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({
    ...updateOpportunityFollowupMutation,
    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: opportunityFollowupSchema
    },
    onSubmit: async ({ value }) => {
      const payload: OpportunityFollowupMutationPayload = {
        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({
          opportunityId,
          followupId: followup.id,
          values: payload
        });
        return;
      }

      await createMutation.mutateAsync({
        opportunityId,
        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 opportunity timeline current with the latest customer interaction and next step.
          </SheetDescription>
        </SheetHeader>

        <div className='flex-1 overflow-auto'>
          <form.AppForm>
            <form.Form id='opportunity-followup-form' className='grid gap-4 md:grid-cols-2'>
              <FormDatePickerField
                name='followupDate'
                label='Follow-up Date'
                required
              />
              <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>
                )}
              />
              <FormDatePickerField
                name='nextFollowupDate'
                label='Next Follow-up Date'
              />
              <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'
                  size='md'
                  label='Outcome'
                  placeholder='Customer asked for revised dimensions and a site survey'
                />
              </div>
              <div className='md:col-span-2'>
                <FormTextareaField
                  name='notes'
                  size='md'
                  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='opportunity-followup-form' isLoading={isPending}>
            <Icons.check className='mr-2 h-4 w-4' />
            {isEdit ? 'Update Follow-up' : 'Create Follow-up'}
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  );
}

