import { useState } from 'react';
import { Pressable, Text, TextInput, View } from 'react-native';
import { toast } from 'sonner-native';
import { BottomSheet } from '@/components/BottomSheet';
import { toUserMessage } from '@/lib/errors';
import { cn } from '@/lib/utils';

interface TaskComposeSheetProps {
  open: boolean;
  onClose: () => void;
  /** Create the task. Must throw on failure so the sheet keeps the draft. */
  onSubmit: (input: { title: string; notes?: string }) => Promise<void>;
}

/**
 * Quick task creator. Mirrors desktop's task-compose-step but pared to the
 * essentials — title (required) plus optional notes. Checklist and assignee
 * are added inline in the task card once it exists.
 */
export function TaskComposeSheet({
  open,
  onClose,
  onSubmit,
}: TaskComposeSheetProps) {
  const [title, setTitle] = useState('');
  const [notes, setNotes] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const [prevOpen, setPrevOpen] = useState(open);
  if (open !== prevOpen) {
    setPrevOpen(open);
    if (open) {
      setTitle('');
      setNotes('');
      setSubmitting(false);
    }
  }

  const trimmedTitle = title.trim();
  const canSend = trimmedTitle.length > 0 && !submitting;

  const handleSubmit = async () => {
    if (!canSend) return;
    setSubmitting(true);
    try {
      await onSubmit({
        title: trimmedTitle,
        notes: notes.trim() || undefined,
      });
      onClose();
    } catch (err) {
      toast.error(toUserMessage(err));
      setSubmitting(false);
    }
  };

  return (
    <BottomSheet open={open} onClose={onClose} avoidKeyboard maxHeight="70%">
      <View className="px-5 pb-4">
        <Text className="text-white text-lg font-semibold">New task</Text>

        <TextInput
          value={title}
          onChangeText={setTitle}
          placeholder="Task title"
          placeholderTextColor="rgba(255,255,255,0.4)"
          autoFocus
          editable={!submitting}
          className="text-white text-base bg-white/10 rounded-xl px-4 py-3 mt-4"
        />

        <TextInput
          value={notes}
          onChangeText={setNotes}
          placeholder="Notes (optional)"
          placeholderTextColor="rgba(255,255,255,0.4)"
          multiline
          editable={!submitting}
          className="text-white text-base bg-white/10 rounded-xl px-4 py-3 mt-3 min-h-20"
        />

        <Pressable
          onPress={handleSubmit}
          disabled={!canSend}
          className={cn(
            'mt-4 rounded-xl py-3 items-center',
            canSend ? 'bg-white' : 'bg-white/20',
          )}
        >
          <Text
            className={cn(
              'text-base font-semibold',
              canSend ? 'text-black' : 'text-white/40',
            )}
          >
            {submitting ? 'Creating…' : 'Create task'}
          </Text>
        </Pressable>
      </View>
    </BottomSheet>
  );
}
