import { useState } from 'react';
import * as Yup from 'yup';
import { useForm, SubmitHandler } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { useRouter } from '@/hooks';
import { useSnackbar } from '@/components/snackbar';
import { transferApi, TransferData } from '@/shared/api/transfer-file';
import { paths } from '@/routes/paths';

// Types
export interface FileData {
  name: string;
  path: string;
  preview?: string;
  size?: number;
  type?: string;
  serverFileName?: string;  
  originalName?: string;
}

export type TransferType = 'email' | 'link';

export interface TransferFormData {
  title: string;
  message: string;
  files: FileData[];
  type: TransferType;
  email_to: string;
}

type TransferFormSchema = Yup.ObjectSchema<TransferFormData>;

export function useTransferNewFile() {
  const router = useRouter();
  const { enqueueSnackbar } = useSnackbar();
  const [isLoading, setIsLoading] = useState(false);
  const [urlsDialog, setUrlsDialog] = useState({
    open: false,
    urls: {} as Record<string, string>,
  });

  const NewFileSchema: TransferFormSchema = Yup.object({
    title: Yup.string().required('Title is required'),
    message: Yup.string().default(''),
    files: Yup.array<FileData>()
      .min(1, 'You are required to import a minimum of one file')
      .required()
      .default([]),
    type: Yup.mixed<TransferType>()
      .oneOf(['email', 'link'])
      .required('Type is required')
      .default('link'),
    email_to: Yup.string()
      .when('type', {
        is: 'email',
        then: (schema) => schema.required('Email is required').email('Email must be valid'),
        otherwise: (schema) => schema.default(''),
      })
      .default(''),
  });

  const methods = useForm<TransferFormData>({
    resolver: yupResolver<TransferFormData>(NewFileSchema),
    defaultValues: {
      title: '',
      message: '',
      files: [],
      type: 'link',
      email_to: '',
    } as TransferFormData,
  });

  const handleTypeChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newType = event.target.value as TransferType;
    methods.setValue('type', newType);
    
    if (newType === 'link') {
      methods.setValue('email_to', '');
    }
  };

  const handleSubmit: SubmitHandler<TransferFormData> = async (data) => {
    setIsLoading(true);

    try {
      if (data.files.length === 0) {
        throw new Error('No files selected');
      }

      const transferData = {
        transferType: data.type.toUpperCase(),
        title: data.title,
        message: data.message,
        recipientEmail: data.email_to,
        files: data.files.map((file) => ({
          name: file.serverFileName || file.name, 
          path: file.serverFileName || file.path, 
          originalName: file.name, 
          size: file.size,
          type: file.type,
        })),
      };


      const result = await transferApi.createTransfer(transferData as TransferData);
    
      if (data.type === 'link') {
        if (result.fileUrls) {
          setUrlsDialog({
            open: true,
            urls: result.fileUrls,
          });
          enqueueSnackbar('Transfer created successfully!');
        } else {
          throw new Error('No URLs received from server');
        }
      } else {
        enqueueSnackbar('Transfer sent by email successfully!');
        router.push(paths.dashboard.transfer.root);
      }
    } catch (error) {
      enqueueSnackbar(
        error instanceof Error ? error.message : 'Failed to transfer files', 
        { variant: 'error' }
      );
    } finally {
      setIsLoading(false);
    }
  };

  const handleCloseUrlsDialog = () => {
    setUrlsDialog(prev => ({ ...prev, open: false }));
    router.push(paths.dashboard.transfer.root);
  };

  return {
    methods,
    isLoading,
    urlsDialog,
    handleSubmit,
    handleTypeChange,
    handleCloseUrlsDialog,
  };
}