import React, { useState } from 'react';
import {
  View,
  ScrollView,
  StyleSheet,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { ScreenContainer } from '../../components/layout/ScreenContainer';
import { Card } from '../../components/common/Card';
import { Input } from '../../components/ui/Input';
import { Button } from '../../components/ui/Button';
import { useToast } from '../../context/ToastContext';
import { useResponsive } from '../../hooks/useResponsive';
import { jobService } from '../../services/jobService';
import { colors, spacing } from '../../theme';

export default function JobCreateScreen() {
  const navigation = useNavigation<any>();
  const { toast } = useToast();
  const { contentPadding, fontSize } = useResponsive();
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [scheduledStart, setScheduledStart] = useState('');
  const [scheduledEnd, setScheduledEnd] = useState('');
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<{ title?: string }>({});

  const validate = () => {
    if (!title.trim()) {
      setErrors({ title: 'Job title is required' });
      return false;
    }
    setErrors({});
    return true;
  };

  const handleCreate = async () => {
    if (!validate()) return;

    setLoading(true);
    try {
      const data: any = { title: title.trim() };
      if (description.trim()) data.description = description.trim();
      if (scheduledStart.trim()) data.scheduled_start = scheduledStart.trim();
      if (scheduledEnd.trim()) data.scheduled_end = scheduledEnd.trim();

      await jobService.create(data);
      toast('Job created successfully', 'success');
      navigation.goBack();
    } catch (error: any) {
      toast(error.response?.data?.error || 'Failed to create job', 'error');
    } finally {
      setLoading(false);
    }
  };

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
    >
      <ScreenContainer
        title="Create Job"
        onBack={() => navigation.goBack()}
        scroll={true}
        contentPadding={contentPadding}
      >
        <Card style={[styles.section, { marginBottom: spacing.xl }]}>
          <Input
            label="Job Title"
            required
            placeholder="Enter job title"
            value={title}
            onChangeText={setTitle}
            error={errors.title}
          />

          <Input
            label="Description"
            placeholder="Enter description"
            value={description}
            onChangeText={setDescription}
            multiline
          />

          <Input
            label="Scheduled Start"
            placeholder="YYYY-MM-DD HH:MM"
            value={scheduledStart}
            onChangeText={setScheduledStart}
            hint="Optional - format: YYYY-MM-DD HH:MM"
          />

          <Input
            label="Scheduled End"
            placeholder="YYYY-MM-DD HH:MM"
            value={scheduledEnd}
            onChangeText={setScheduledEnd}
            hint="Optional - format: YYYY-MM-DD HH:MM"
          />
        </Card>

        <Button
          title="Create Job"
          onPress={handleCreate}
          loading={loading}
          disabled={loading}
          size="lg"
          style={{ marginTop: spacing.sm }}
        />
      </ScreenContainer>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  section: {},
});
