import React, { useState, useEffect } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
import { Container, Form, Button, Card, Row, Col, Alert } from 'react-bootstrap';
import { Formik } from 'formik';
import * as Yup from 'yup';
import { FaArrowLeft, FaSave } from 'react-icons/fa';
import api from '../../utils/api';
import LoadingSpinner from '../common/LoadingSpinner';

// Validation schema
const projectSchema = Yup.object().shape({
  name: Yup.string().required('Project name is required'),
  description: Yup.string(),
  start_date: Yup.date().nullable(),
  end_date: Yup.date().nullable().min(
    Yup.ref('start_date'),
    'End date must be after start date'
  ),
  completion_percentage: Yup.number()
    .min(0, 'Percentage must be at least 0')
    .max(100, 'Percentage must be at most 100')
    .required('Completion percentage is required'),
  notes: Yup.string()
});

const ProjectForm = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [project, setProject] = useState(null);
  const [loading, setLoading] = useState(id ? true : false);
  const [error, setError] = useState(null);
  const isEditMode = !!id;

  // Initial form values
  const initialValues = {
    name: '',
    description: '',
    start_date: '',
    end_date: '',
    completion_percentage: 0,
    notes: ''
  };

  useEffect(() => {
    // If in edit mode, fetch project data
    if (isEditMode) {
      fetchProject();
    }
  }, [id]);

  const fetchProject = async () => {
    try {
      setLoading(true);
      const response = await api.get(`/projects/${id}`);
      
      // Format dates for form inputs (YYYY-MM-DD)
      const projectData = response.data;
      if (projectData.start_date) {
        projectData.start_date = new Date(projectData.start_date).toISOString().split('T')[0];
      }
      if (projectData.end_date) {
        projectData.end_date = new Date(projectData.end_date).toISOString().split('T')[0];
      }
      
      setProject(projectData);
      setError(null);
    } catch (err) {
      console.error('Error fetching project:', err);
      setError('Failed to load project data.');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (values, { setSubmitting }) => {
    try {
      if (isEditMode) {
        await api.put(`/projects/${id}`, values);
      } else {
        await api.post('/projects', values);
      }
      
      navigate('/dashboard');
    } catch (err) {
      console.error('Error saving project:', err);
      setError(err.response?.data?.message || 'Failed to save project.');
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) return <LoadingSpinner />;

  return (
    <Container>
      <Button 
        as={Link} 
        to="/dashboard" 
        variant="outline-secondary" 
        className="mb-3"
      >
        <FaArrowLeft className="me-1" /> Back to Dashboard
      </Button>

      <Card className="shadow-sm">
        <Card.Header className="bg-primary text-white">
          <h3 className="mb-0">{isEditMode ? 'Edit Project' : 'Create New Project'}</h3>
        </Card.Header>
        
        <Card.Body>
          {error && <Alert variant="danger">{error}</Alert>}
          
          <Formik
            initialValues={project || initialValues}
            validationSchema={projectSchema}
            onSubmit={handleSubmit}
            enableReinitialize
          >
            {({
              values,
              errors,
              touched,
              handleChange,
              handleBlur,
              handleSubmit,
              isSubmitting,
            }) => (
              <Form onSubmit={handleSubmit}>
                <Row>
                  <Col md={6}>
                    <Form.Group className="mb-3">
                      <Form.Label>Project Name *</Form.Label>
                      <Form.Control
                        type="text"
                        name="name"
                        value={values.name}
                        onChange={handleChange}
                        onBlur={handleBlur}
                        isInvalid={touched.name && errors.name}
                      />
                      <Form.Control.Feedback type="invalid">
                        {errors.name}
                      </Form.Control.Feedback>
                    </Form.Group>
                    
                    <Form.Group className="mb-3">
                      <Form.Label>Start Date</Form.Label>
                      <Form.Control
                        type="date"
                        name="start_date"
                        value={values.start_date}
                        onChange={handleChange}
                        onBlur={handleBlur}
                        isInvalid={touched.start_date && errors.start_date}
                      />
                      <Form.Control.Feedback type="invalid">
                        {errors.start_date}
                      </Form.Control.Feedback>
                    </Form.Group>
                    
                    <Form.Group className="mb-3">
                      <Form.Label>End Date</Form.Label>
                      <Form.Control
                        type="date"
                        name="end_date"
                        value={values.end_date}
                        onChange={handleChange}
                        onBlur={handleBlur}
                        isInvalid={touched.end_date && errors.end_date}
                      />
                      <Form.Control.Feedback type="invalid">
                        {errors.end_date}
                      </Form.Control.Feedback>
                    </Form.Group>
                  </Col>
                  
                  <Col md={6}>
                    <Form.Group className="mb-3">
                      <Form.Label>Completion Percentage *</Form.Label>
                      <div className="d-flex align-items-center">
                        <Form.Control
                          type="range"
                          name="completion_percentage"
                          min="0"
                          max="100"
                          step="5"
                          value={values.completion_percentage}
                          onChange={handleChange}
                          onBlur={handleBlur}
                          className="me-2"
                        />
                        <span>{values.completion_percentage}%</span>
                      </div>
                      {touched.completion_percentage && errors.completion_percentage && (
                        <div className="text-danger">{errors.completion_percentage}</div>
                      )}
                    </Form.Group>
                    
                    <Form.Group className="mb-3">
                      <Form.Label>Description</Form.Label>
                      <Form.Control
                        as="textarea"
                        rows={3}
                        name="description"
                        value={values.description}
                        onChange={handleChange}
                        onBlur={handleBlur}
                        isInvalid={touched.description && errors.description}
                      />
                      <Form.Control.Feedback type="invalid">
                        {errors.description}
                      </Form.Control.Feedback>
                    </Form.Group>
                    
                    <Form.Group className="mb-3">
                      <Form.Label>Additional Notes</Form.Label>
                      <Form.Control
                        as="textarea"
                        rows={3}
                        name="notes"
                        value={values.notes}
                        onChange={handleChange}
                        onBlur={handleBlur}
                        isInvalid={touched.notes && errors.notes}
                      />
                      <Form.Control.Feedback type="invalid">
                        {errors.notes}
                      </Form.Control.Feedback>
                    </Form.Group>
                  </Col>
                </Row>
                
                <div className="d-flex justify-content-end mt-3">
                  <Button 
                    type="submit" 
                    variant="primary" 
                    disabled={isSubmitting}
                  >
                    <FaSave className="me-1" />
                    {isSubmitting ? 'Saving...' : 'Save Project'}
                  </Button>
                </div>
              </Form>
            )}
          </Formik>
        </Card.Body>
      </Card>
    </Container>
  );
};

export default ProjectForm;
