import { useEffect, useMemo, useState } from 'react';
import api from '../services/api';
import PwaBottomSheet from './PwaBottomSheet';
import PwaTaskFormFields from './PwaTaskFormFields';
import { usePwaNotification } from './PwaNotificationProvider';

const initialForm = {
  title: '',
  project_id: '',
  assignee_id: '',
  priority: 'medium',
  due_date: '',
  description: '',
};

function normalizeErrors(error) {
  const apiErrors = error.response?.data?.errors;
  if (apiErrors) return apiErrors;

  return {
    form: error.response?.data?.message || 'خطا در ثبت تسک. لطفاً دوباره تلاش کنید.',
  };
}

export default function PwaCreateTaskSheet({ open, onClose, initialProjectId = '', lockProject = false, successMessage = 'تسک با موفقیت ایجاد شد.', onCreated }) {
  const { notify } = usePwaNotification();
  const [form, setForm] = useState(initialForm);
  const [errors, setErrors] = useState({});
  const [options, setOptions] = useState({ projects: [], users: [], priorities: [] });
  const [loadingOptions, setLoadingOptions] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const hasProjects = options.projects.length > 0;
  const canSubmit = useMemo(() => form.title.trim() && form.project_id && !submitting, [form.project_id, form.title, submitting]);

  useEffect(() => {
    if (!open) return;

    setErrors({});
    setForm((current) => ({ ...current, project_id: initialProjectId || current.project_id, assignee_id: initialProjectId ? '' : current.assignee_id }));
    setLoadingOptions(true);
    api.get('/pwa/task-options')
      .then(({ data }) => setOptions(data.data || { projects: [], users: [], priorities: [] }))
      .catch((error) => {
        setErrors(normalizeErrors(error));
        notify({
          tone: 'error',
          title: 'ایجاد تسک',
          message: error.response?.data?.message || 'دریافت گزینه‌های فرم ممکن نشد.',
        });
      })
      .finally(() => setLoadingOptions(false));
  }, [initialProjectId, notify, open]);

  const handleChange = (field, value) => {
    setForm((current) => {
      const next = { ...current, [field]: value };
      if (field === 'project_id') next.assignee_id = '';
      return next;
    });
    setErrors((current) => ({ ...current, [field]: null, form: null }));
  };

  const handleClose = () => {
    if (submitting) return;
    onClose();
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    if (submitting) return;

    if (!form.title.trim() || !form.project_id) {
      setErrors({
        title: !form.title.trim() ? 'عنوان تسک الزامی است.' : null,
        project_id: !form.project_id ? 'انتخاب پروژه الزامی است.' : null,
      });
      return;
    }

    setSubmitting(true);
    setErrors({});

    try {
      const payload = {
        title: form.title.trim(),
        project_id: form.project_id,
        assignee_id: form.assignee_id || null,
        priority: form.priority || 'medium',
        status: 'todo',
        due_date: form.due_date || null,
        description: form.description.trim() || null,
      };
      const { data } = await api.post('/tasks', payload);
      setForm(initialForm);
      onClose();
      notify({
        tone: 'success',
        title: 'تسک جدید',
        message: successMessage,
        actionLabel: 'مشاهده تسک',
        target: { available: true, path: '/pwa/tasks' },
      });
      onCreated?.(data.data);
      window.dispatchEvent(new CustomEvent('pwa:task-created', { detail: data.data }));
    } catch (error) {
      const nextErrors = normalizeErrors(error);
      setErrors(nextErrors);
      notify({
        tone: 'error',
        title: 'ثبت تسک ناموفق بود',
        message: nextErrors.form || 'اطلاعات فرم را بررسی کنید.',
      });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <PwaBottomSheet
      open={open}
      title="ایجاد تسک"
      onClose={handleClose}
      footer={(
        <>
          <button type="button" className="pwa-sheet-cancel" onClick={handleClose} disabled={submitting}>انصراف</button>
          <button type="submit" form="pwa-create-task-form" className="pwa-sheet-submit" disabled={!canSubmit}>
            {submitting ? 'در حال ثبت...' : 'ثبت تسک'}
          </button>
        </>
      )}
    >
      <form id="pwa-create-task-form" onSubmit={handleSubmit}>
        {errors.form && <div className="pwa-form-error">{errors.form}</div>}
        {loadingOptions ? (
          <div className="pwa-form-loading">در حال آماده‌سازی فرم...</div>
        ) : !hasProjects ? (
          <div className="pwa-form-error">پروژه‌ای برای ایجاد تسک در دسترس شما نیست.</div>
        ) : (
          <PwaTaskFormFields
            form={form}
            errors={errors}
            projects={options.projects}
            users={options.users}
            priorities={options.priorities}
            lockProject={lockProject}
            onChange={handleChange}
          />
        )}
      </form>
    </PwaBottomSheet>
  );
}
