import React from 'react';
import { View, Text, StyleSheet, SafeAreaView, ScrollView, KeyboardAvoidingView, Platform, TouchableOpacity } from 'react-native';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { Header } from '@/components/Header';
import { CategorySelector } from '@/components/CategorySelector';
import { TaskNameInput } from '@/components/TaskNameInput';
import { SubtasksSection } from '@/components/SubtasksSection';
import { DateTimePickerComponent } from '@/components/DateTimePicker';
import { PrioritySelector } from '@/components/PrioritySelector';
import { RepeatSelector } from '@/components/RepeatSelector';
import { ReminderSelector } from '@/components/ReminderSelector';
import { DescriptionInput } from '@/components/DescriptionInput';
import { FormButtons } from '@/components/FormButtons';
import { TaskDeleteModal } from '@/components/TaskDeleteModal';
import { AssigneeSelector } from '@/components/AssigneeSelector';
import { useForm, FormProvider, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useDatabase } from '@/hooks/useDatabase';
import { database, collections } from '@/database';
import { Q } from '@nozbe/watermelondb';
import { TaskFormData } from '@/types';
import { useSettings } from '@/theme';
import { deleteTaskOccurrences } from '@/utils/taskActions';
import { scheduleTaskReminder, cancelTaskReminder } from '@/services/notifications';
import { useFriends } from '@/hooks/useFriends';
import Svg, { Path } from 'react-native-svg';

const taskSchema = z.object({
  title: z.string().trim().min(1, 'Task name is required').max(100),
  description: z.string().max(1000).optional(),
  categoryId: z.string().min(1, 'Category is required'),
  priority: z.enum(['none', 'low', 'medium', 'high', 'critical']),
  dueDate: z.date().nullable().optional(),
  dueTime: z.string().optional(),
  endTime: z.string().optional(),
  allDay: z.boolean().optional(),
  repeat: z.enum(['none', 'daily', 'weekly', 'monthly', 'custom']),
  repeatInterval: z.number().int().min(1).max(30).optional(),
  repeatDays: z.array(z.number().int().min(0).max(6)).optional(),
  reminder: z.enum(['none', 'at_time', '15', '30', '60', '120', '1440']),
  assigneeId: z.string().nullable().optional(),
  subtasks: z.array(z.object({ title: z.string(), _key: z.string().optional() })).optional(),
});

export default function TaskDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const { isReady } = useDatabase();
  const router = useRouter();
  const { theme } = useSettings();
  const { friends } = useFriends();
  const [loaded, setLoaded] = React.useState(false);
  const [notFound, setNotFound] = React.useState(false);

  const methods = useForm<TaskFormData>({
    resolver: zodResolver(taskSchema),
    defaultValues: {
      title: '',
      description: '',
      categoryId: '',
      priority: 'none',
      dueDate: null,
      dueTime: '',
      endTime: '',
      allDay: false,
      repeat: 'none',
      repeatInterval: 1,
      repeatDays: [],
      reminder: 'none',
      assigneeId: null,
      subtasks: [],
    },
  });

  const { handleSubmit, watch, setValue, control, reset, formState: { errors } } = methods;

  const categoryId = watch('categoryId');
  const priority = watch('priority');
  const repeat = watch('repeat');
  const repeatInterval = watch('repeatInterval') ?? 1;
  const repeatDays = watch('repeatDays') ?? [];
  const reminder = watch('reminder');
  const dueDate = watch('dueDate');
  const assigneeId = watch('assigneeId');
  const [deleteModalVisible, setDeleteModalVisible] = React.useState(false);

  React.useEffect(() => {
    if (!id || !isReady) return;
    let mounted = true;

    (async () => {
      try {
        const task = await collections.tasks.find(id);
        const subtasks = await collections.subtasks.query(Q.where('task_id', id)).fetch();

        if (!mounted) return;
        reset({
          title: task.title,
          description: task.description,
          categoryId: task.categoryId,
          priority: task.priority,
          dueDate: task.dueDate ? new Date(task.dueDate) : null,
          dueTime: task.dueTime,
          endTime: task.endTime || '',
          allDay: task.allDay ?? false,
          repeat: task.repeat,
          repeatInterval: task.repeatInterval || 1,
          repeatDays: (task.repeatDays || '').split(',').map(Number).filter((d) => !Number.isNaN(d)),
          reminder: (task.reminder || 'none') as TaskFormData['reminder'],
          assigneeId: task.assigneeId ?? null,
          subtasks: subtasks.map((s) => ({ title: s.title, _key: s.id })),
        });
        setLoaded(true);
      } catch {
        if (mounted) setNotFound(true);
      }
    })();

    return () => { mounted = false; };
  }, [id, isReady, reset]);

  const onSubmit = async (data: TaskFormData) => {
    if (!id || !isReady) return;

    const now = new Date();
    const dueDateTimestamp = data.dueDate ? data.dueDate.getTime() : 0;

    let savedTask: any = null;

    await database.write(async () => {
      const task = await collections.tasks.find(id);
      savedTask = task;
      const existingSubtasks = await collections.subtasks.query(Q.where('task_id', id)).fetch();
      for (const subtask of existingSubtasks) {
        await subtask.destroyPermanently();
      }

      await task.update((t) => {
        t.title = data.title.trim();
        t.description = data.description || '';
        t.categoryId = data.categoryId;
        t.priority = data.priority;
        t.dueDate = dueDateTimestamp;
        t.dueTime = data.dueTime || '';
        t.endTime = data.endTime || '';
        t.allDay = data.allDay ?? false;
        t.repeat = data.repeat;
        t.repeatInterval = data.repeatInterval || 1;
        t.repeatDays = (data.repeatDays || []).join(',');
        t.reminder = data.reminder || 'none';
        t.assigneeId = data.assigneeId ?? null;
        if (data.repeat !== 'none' && !t.seriesId) {
          t.seriesId = `series_${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;
        }
        t.updatedAt = now;
      });

      if (data.subtasks && data.subtasks.length > 0) {
        for (let i = 0; i < data.subtasks.length; i++) {
          const subtask = data.subtasks[i];
          if (subtask.title.trim()) {
            await collections.subtasks.create((s) => {
              s.taskId = task.id;
              s.title = subtask.title.trim();
              s.description = '';
              s.priority = 'none';
              s.completed = false;
              s.dueDate = 0;
              s.dueTime = '';
              s.endTime = '';
              s.allDay = false;
              s.repeat = 'none';
              s.repeatInterval = 1;
              s.repeatDays = '';
              s.seriesId = '';
              s.reminder = 'none';
              s.assigneeId = null;
              s.order = i;
              s.createdAt = now;
              s.updatedAt = now;
            });
          }
        }
      }
    });

    await scheduleTaskReminder(savedTask);

    router.back();
  };

  const handleDelete = () => {
    setDeleteModalVisible(true);
  };

  const doDelete = async (scope: 'this' | 'future' | 'all') => {
    if (!id) return;
    setDeleteModalVisible(false);
    await deleteTaskOccurrences(id, scope);
    router.back();
  };

  if (!isReady || !loaded) {
    return (
      <View style={[styles.loadingContainer, { backgroundColor: theme.background }]}>
        <Text style={{ color: theme.textFaint }}>{notFound ? 'Task not found' : 'Loading...'}</Text>
      </View>
    );
  }

  return (
    <SafeAreaView style={[styles.container, { backgroundColor: theme.background }]}>
      <Header
        title="Edit Task"
        showLogo={true}
        rightAction={
          <TouchableOpacity onPress={handleDelete} activeOpacity={0.7} style={[styles.deleteButton, { borderColor: theme.accentBorder, backgroundColor: theme.accentSoft }]}>
            <Svg width={22} height={22} viewBox="0 0 24 24">
              <Path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13" stroke={theme.accent} strokeWidth={1.8} strokeLinecap="round" strokeLinejoin="round" fill="none" />
            </Svg>
          </TouchableOpacity>
        }
      />
      <FormProvider {...methods}>
        <KeyboardAvoidingView
          style={styles.keyboardAvoiding}
          behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        >
          <ScrollView
            contentContainerStyle={styles.scrollContent}
            showsVerticalScrollIndicator={false}
            keyboardShouldPersistTaps="handled"
          >
            <CategorySelector
              value={categoryId}
              onChange={(value) => setValue('categoryId', value)}
              error={errors.categoryId?.message}
            />
            <Controller
              control={control}
              name="title"
              render={({ field }) => (
                <TaskNameInput
                  value={field.value}
                  onChangeText={field.onChange}
                  onBlur={field.onBlur}
                  error={errors.title?.message}
                />
              )}
            />
            <SubtasksSection control={control} />
            <PrioritySelector
              value={priority}
              onChange={(value) => setValue('priority', value)}
            />
            <DateTimePickerComponent control={control} />
            <RepeatSelector
              value={repeat}
              interval={repeatInterval}
              days={repeatDays}
              onChange={(nextRepeat, nextInterval, nextDays) => {
                setValue('repeat', nextRepeat);
                setValue('repeatInterval', nextInterval);
                setValue('repeatDays', nextDays);
              }}
            />
            <ReminderSelector
              value={reminder}
              hasDueDate={!!dueDate}
              onChange={(value) => setValue('reminder', value)}
            />
            <AssigneeSelector
              value={assigneeId}
              onChange={(value: string | null) => setValue('assigneeId', value)}
              friends={friends.map((f) => f.username)}
            />
            <Controller
              control={control}
              name="description"
              render={({ field }) => (
                <DescriptionInput
                  value={field.value ?? ''}
                  onChangeText={field.onChange}
                  onBlur={field.onBlur}
                />
              )}
            />
          </ScrollView>
        </KeyboardAvoidingView>
        <FormButtons onSubmit={handleSubmit(onSubmit)} submitLabel="Save" />
      </FormProvider>

      <TaskDeleteModal
        visible={deleteModalVisible}
        taskId={id}
        taskTitle={methods.getValues('title')}
        isRepeating={repeat !== 'none'}
        onClose={() => setDeleteModalVisible(false)}
        onDelete={doDelete}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  keyboardAvoiding: {
    flex: 1,
  },
  scrollContent: {
    paddingHorizontal: 16,
    paddingTop: 8,
    paddingBottom: 100,
    gap: 24,
  },
  deleteButton: {
    width: 36,
    height: 36,
    borderRadius: 12,
    borderWidth: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});
