import React, { useCallback, useRef, useState } from 'react';
import { View, Text, StyleSheet, Modal, TextInput, TouchableOpacity } from 'react-native';
import { useRouter } from 'expo-router';
import { TaskData, SubtaskData } from '@/types';
import { PRIORITY_LABELS } from '@/constants';
import { useCategories } from '@/hooks/useDatabase';
import { useSettings } from '@/theme';
import { TaskOverflowMenu } from '@/components/TaskOverflowMenu';
import { TaskDeleteModal } from '@/components/TaskDeleteModal';
import { OptionPickerModal } from '@/components/OptionPickerModal';
import {
  toggleTaskComplete,
  deleteTaskOccurrences,
  duplicateTask,
  setTaskCategory,
  setTaskPriority,
  toggleSubtaskComplete,
  deleteSubtask,
  duplicateSubtask,
  setSubtaskPriority,
  createSubtask,
  TaskDeleteScope,
} from '@/utils/taskActions';

const PRIORITY_OPTIONS = Object.entries(PRIORITY_LABELS).map(([value, label]) => ({ value, label }));

interface AddSubtaskModalProps {
  visible: boolean;
  parentSubtask: SubtaskData | null;
  onClose: () => void;
  onAdd: (title: string) => void;
}

function AddSubtaskModal({ visible, parentSubtask, onClose, onAdd }: AddSubtaskModalProps) {
  const { theme } = useSettings();
  const [title, setTitle] = React.useState('');

  React.useEffect(() => {
    if (visible) {
      setTitle('');
    }
  }, [visible]);

  const handleSubmit = () => {
    if (title.trim()) {
      onAdd(title.trim());
    }
  };

  if (!visible || !parentSubtask) return null;

  const styles = StyleSheet.create({
    overlay: {
      flex: 1,
      justifyContent: 'flex-end',
    },
    sheet: {
      borderTopLeftRadius: 24,
      borderTopRightRadius: 24,
      paddingTop: 8,
      paddingHorizontal: 16,
      paddingBottom: 32,
    },
    handle: {
      width: 40,
      height: 4,
      borderRadius: 2,
      alignSelf: 'center',
      marginBottom: 12,
    },
    title: {
      fontSize: 16,
      fontWeight: '600',
      textAlign: 'center',
      marginBottom: 16,
      color: theme.text,
    },
    inputContainer: {
      marginBottom: 16,
    },
    input: {
      fontSize: 16,
      paddingHorizontal: 16,
      paddingVertical: 12,
      borderRadius: 12,
      borderWidth: 1,
      color: theme.text,
      backgroundColor: theme.card,
      borderColor: theme.border,
    },
    buttonRow: {
      flexDirection: 'row',
      gap: 8,
    },
    button: {
      flex: 1,
      paddingVertical: 14,
      borderRadius: 12,
      alignItems: 'center',
    },
    buttonText: {
      fontSize: 16,
      fontWeight: '600',
      color: '#FFFFFF',
    },
    buttonCancel: {
      backgroundColor: theme.card,
      borderWidth: 1,
      borderColor: theme.border,
    },
    buttonAdd: {
      backgroundColor: theme.accent,
    },
  });

  return (
    <Modal visible={visible} transparent animationType="fade" onRequestClose={onClose}>
      <TouchableOpacity
        style={[styles.overlay, { backgroundColor: theme.overlay }]}
        activeOpacity={1}
        onPress={onClose}
      >
        <View style={[styles.sheet, { backgroundColor: theme.sheetBg }]}>
          <View style={[styles.handle, { backgroundColor: theme.borderStrong }]} />
          <Text style={styles.title}>
            Add Subtask to &ldquo;{parentSubtask.title}&rdquo;
          </Text>
          <View style={styles.inputContainer}>
            <TextInput
              style={styles.input}
              placeholder="Subtask name"
              value={title}
              onChangeText={setTitle}
              autoCapitalize="sentences"
              maxLength={100}
              autoFocus
              onSubmitEditing={handleSubmit}
            />
          </View>
          <View style={styles.buttonRow}>
            <TouchableOpacity style={styles.buttonCancel} onPress={onClose} activeOpacity={0.7}>
              <Text style={styles.buttonText}>Cancel</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.buttonAdd} onPress={handleSubmit} activeOpacity={0.7}>
              <Text style={styles.buttonText}>Add</Text>
            </TouchableOpacity>
          </View>
        </View>
      </TouchableOpacity>
    </Modal>
  );
}

export function useTaskModals() {
  const router = useRouter();
  const categories = useCategories();

  const [menuTask, setMenuTask] = useState<TaskData | null>(null);
  const [menuSubtask, setMenuSubtask] = useState<SubtaskData | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<TaskData | null>(null);
  const [deleteSubtaskTarget, setDeleteSubtaskTarget] = useState<SubtaskData | null>(null);
  const [picker, setPicker] = useState<null | { type: 'category' | 'priority'; taskId?: string }>(null);
  const [subtaskPicker, setSubtaskPicker] = useState<null | { type: 'priority'; subtaskId?: string }>(null);
  const [addSubtaskTarget, setAddSubtaskTarget] = useState<SubtaskData | null>(null);
  const refreshRef = useRef<() => void>(() => {});

  const openTaskMenu = useCallback((task: TaskData) => setMenuTask(task), []);
  const openSubtaskMenu = useCallback((subtask: SubtaskData) => setMenuSubtask(subtask), []);
  const openTaskDelete = useCallback((task: TaskData) => setDeleteTarget(task), []);
  const openSubtaskDelete = useCallback((subtask: SubtaskData) => setDeleteSubtaskTarget(subtask), []);
  const openTaskEdit = useCallback((taskId: string) => {
    router.push({ pathname: '/task-detail', params: { id: taskId } });
  }, [router]);
  const openSubtaskEdit = useCallback((subtaskId: string) => {
    router.push({ pathname: '/subtask-detail', params: { id: subtaskId } });
  }, [router]);
  const openSubtaskAdd = useCallback((subtask: SubtaskData) => {
    setAddSubtaskTarget(subtask);
  }, []);

  const handleToggleComplete = useCallback(async (taskId: string) => {
    await toggleTaskComplete(taskId);
    refreshRef.current();
  }, []);

  const handleSubtaskToggle = useCallback(async (subtask: SubtaskData) => {
    await toggleSubtaskComplete(subtask.id);
    refreshRef.current();
  }, []);

  const handleDuplicate = useCallback(async (taskId: string) => {
    await duplicateTask(taskId);
    refreshRef.current();
  }, []);

  const handleSubtaskDuplicate = useCallback(async (subtaskId: string) => {
    await duplicateSubtask(subtaskId);
    refreshRef.current();
  }, []);

  const handleDeleteScope = useCallback(async (scope: TaskDeleteScope) => {
    const target = deleteTarget;
    if (!target) return;
    setDeleteTarget(null);
    await deleteTaskOccurrences(target.id, scope);
    refreshRef.current();
  }, [deleteTarget]);

  const handleDeleteSubtask = useCallback(async () => {
    const target = deleteSubtaskTarget;
    if (!target) return;
    setDeleteSubtaskTarget(null);
    await deleteSubtask(target.id);
    refreshRef.current();
  }, [deleteSubtaskTarget]);

  const handleSingleCategory = useCallback(async (value: string | string[]) => {
    if (picker?.taskId) {
      await setTaskCategory(picker.taskId, Array.isArray(value) ? value[0] : value);
      refreshRef.current();
    }
  }, [picker]);

  const handleSinglePriority = useCallback(async (value: string | string[]) => {
    if (picker?.taskId) {
      await setTaskPriority(picker.taskId, (Array.isArray(value) ? value[0] : value) as TaskData['priority']);
      refreshRef.current();
    }
  }, [picker]);

  const handleSubtaskPriority = useCallback(async (value: string | string[]) => {
    if (subtaskPicker?.subtaskId) {
      await setSubtaskPriority(subtaskPicker.subtaskId, (Array.isArray(value) ? value[0] : value) as TaskData['priority']);
      refreshRef.current();
    }
  }, [subtaskPicker]);

  const handleAddSubtask = useCallback(async (title: string) => {
    const target = addSubtaskTarget;
    if (!target || !title.trim()) return;
    await createSubtask({
      taskId: target.taskId,
      parentSubtaskId: target.id,
      title: title.trim(),
    });
    setAddSubtaskTarget(null);
    refreshRef.current();
  }, [addSubtaskTarget]);

  const modals = (refresh: () => void) => {
    refreshRef.current = refresh;
    return (
      <>
        <TaskDeleteModal
          visible={deleteTarget !== null}
          taskId={deleteTarget?.id ?? null}
          taskTitle={deleteTarget?.title}
          isRepeating={deleteTarget ? deleteTarget.repeat !== 'none' : false}
          onClose={() => setDeleteTarget(null)}
          onDelete={handleDeleteScope}
        />

        <TaskDeleteModal
          visible={deleteSubtaskTarget !== null}
          taskId={deleteSubtaskTarget?.id ?? null}
          taskTitle={deleteSubtaskTarget?.title}
          subtask
          onClose={() => setDeleteSubtaskTarget(null)}
          onDelete={handleDeleteSubtask}
        />

        <TaskOverflowMenu
          visible={menuTask !== null}
          task={menuTask}
          onClose={() => setMenuTask(null)}
          onEdit={() => menuTask && openTaskEdit(menuTask.id)}
          onDelete={() => menuTask && openTaskDelete(menuTask)}
          onDuplicate={() => menuTask && handleDuplicate(menuTask.id)}
          onToggleComplete={() => menuTask && handleToggleComplete(menuTask.id)}
          onChangeCategory={() => menuTask && setPicker({ type: 'category', taskId: menuTask.id })}
          onChangePriority={() => menuTask && setPicker({ type: 'priority', taskId: menuTask.id })}
        />

        <TaskOverflowMenu
          visible={menuSubtask !== null}
          task={menuSubtask}
          subtask
          onClose={() => setMenuSubtask(null)}
          onEdit={() => menuSubtask && openSubtaskEdit(menuSubtask.id)}
          onDelete={() => menuSubtask && openSubtaskDelete(menuSubtask)}
          onDuplicate={() => menuSubtask && handleSubtaskDuplicate(menuSubtask.id)}
          onToggleComplete={() => menuSubtask && handleSubtaskToggle(menuSubtask)}
          onChangePriority={() => menuSubtask && setSubtaskPicker({ type: 'priority', subtaskId: menuSubtask.id })}
          onAddSubtask={() => menuSubtask && openSubtaskAdd(menuSubtask)}
        />

        <AddSubtaskModal
          visible={addSubtaskTarget !== null}
          parentSubtask={addSubtaskTarget}
          onClose={() => setAddSubtaskTarget(null)}
          onAdd={handleAddSubtask}
        />

        <OptionPickerModal
          visible={picker?.type === 'category'}
          title="Change Category"
          options={[{ value: '', label: 'None', color: '#9E9E9E' }, ...categories.map((c) => ({ value: c.id, label: c.name, color: c.color }))]}
          selectedValue={menuTask?.categoryId}
          onSelect={handleSingleCategory}
          onClose={() => setPicker(null)}
        />

        <OptionPickerModal
          visible={picker?.type === 'priority'}
          title="Change Priority"
          options={PRIORITY_OPTIONS}
          selectedValue={menuTask?.priority}
          onSelect={handleSinglePriority}
          onClose={() => setPicker(null)}
        />

<OptionPickerModal
          visible={subtaskPicker?.type === 'priority'}
          title="Change Priority"
          options={PRIORITY_OPTIONS}
          selectedValue={menuSubtask?.priority}
          onSelect={handleSubtaskPriority}
          onClose={() => setSubtaskPicker(null)}
        />
      </>
    );
  };

  return {
    modals,
    openTaskMenu,
    openSubtaskMenu,
    openTaskDelete,
    openSubtaskDelete,
    openTaskEdit,
    openSubtaskEdit,
    openSubtaskAdd,
  };
}
