import { AlertCircle, FolderKanban, Search } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { useAuth } from '../context/AuthContext';
import api from '../services/api';
import PwaCreateTaskSheet from './PwaCreateTaskSheet';
import PwaProjectCard from './PwaProjectCard';
import PwaProjectFilters, { getProjectFilter } from './PwaProjectFilters';
import PwaProjectStatusSheet from './PwaProjectStatusSheet';
import { usePwaNotification } from './PwaNotificationProvider';
import { hasPermission } from './pwaTaskMeta';

export default function PwaProjectsPage() {
  const { user } = useAuth();
  const { notify } = usePwaNotification();
  const [projects, setProjects] = useState([]);
  const [filter, setFilter] = useState('all');
  const [search, setSearch] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [createProject, setCreateProject] = useState(null);
  const [statusProject, setStatusProject] = useState(null);
  const canView = useMemo(() => hasPermission(user, 'projects.view'), [user]);
  const permissions = useMemo(() => ({
    canCreateTask: hasPermission(user, 'tasks.create'),
    canEditProject: hasPermission(user, 'projects.edit'),
  }), [user]);
  const activeFilter = getProjectFilter(filter);

  const fetchProjects = async () => {
    setLoading(true);
    setError('');
    try {
      const { data } = await api.get('/pwa/projects', { params: { filter, search: search.trim() || undefined, per_page: 30 } });
      setProjects(data.data || []);
    } catch (err) {
      setError(err.response?.data?.message || 'خطا در دریافت اطلاعات پروژه‌ها. دوباره تلاش کنید.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const timer = window.setTimeout(fetchProjects, 260);
    return () => window.clearTimeout(timer);
  }, [filter, search]);

  const changeProjectStatus = async (status) => {
    if (!statusProject) return;
    try {
      const { data } = await api.patch(`/pwa/projects/${statusProject.id}/status`, { status });
      setProjects((current) => current.map((project) => project.id === statusProject.id ? { ...project, ...data.data } : project));
      setStatusProject(null);
      notify({ tone: 'success', title: 'پروژه', message: 'وضعیت پروژه تغییر کرد.' });
    } catch (err) {
      notify({ tone: 'error', title: 'پروژه', message: err.response?.data?.message || 'تغییر وضعیت پروژه انجام نشد.' });
    }
  };

  if (!canView) {
    return (
      <section className="pwa-state-card error">
        <AlertCircle size={28} />
        <strong>شما مجوز مشاهده پروژه‌ها را ندارید.</strong>
      </section>
    );
  }

  return (
    <div className="pwa-projects-page">
      <label className="pwa-search-field">
        <Search size={18} />
        <input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="جستجوی پروژه" />
      </label>

      <PwaProjectFilters value={filter} onChange={setFilter} />

      {loading ? (
        <div className="pwa-project-list">
          {[1, 2, 3].map((item) => <div className="pwa-skeleton project-card" key={item} />)}
        </div>
      ) : error ? (
        <section className="pwa-state-card error">
          <AlertCircle size={28} />
          <strong>{error}</strong>
          <button type="button" onClick={fetchProjects}>تلاش دوباره</button>
        </section>
      ) : projects.length ? (
        <div className="pwa-project-list">
          {projects.map((project) => (
            <PwaProjectCard
              key={project.id}
              project={project}
              permissions={permissions}
              onCreateTask={setCreateProject}
              onStatus={setStatusProject}
            />
          ))}
        </div>
      ) : (
        <section className="pwa-empty-card">
          <FolderKanban size={28} />
          <strong>{activeFilter.empty}</strong>
        </section>
      )}

      <PwaCreateTaskSheet
        open={Boolean(createProject)}
        onClose={() => setCreateProject(null)}
        initialProjectId={createProject?.id || ''}
        lockProject
        successMessage="تسک جدید برای این پروژه ایجاد شد."
        onCreated={fetchProjects}
      />
      <PwaProjectStatusSheet open={Boolean(statusProject)} project={statusProject} onClose={() => setStatusProject(null)} onChange={changeProjectStatus} />
    </div>
  );
}
