import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { FaArrowLeft, FaFolderOpen, FaSync, FaExclamationTriangle, FaTasks } from 'react-icons/fa';
import projectService, { type Project, type TaskRow } from '../services/projectService';

function formatDate(d?: string) {
  if (!d) return '—';
  try {
    return new Date(d).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
  } catch {
    return d;
  }
}

function daysBetween(a?: string, b?: string): number | null {
  if (!a || !b) return null;
  const t0 = new Date(a).getTime();
  const t1 = new Date(b).getTime();
  if (Number.isNaN(t0) || Number.isNaN(t1)) return null;
  return Math.max(0, Math.round((t1 - t0) / (24 * 3600 * 1000)));
}

function MiniBar({ label, pct, colorClass }: { label: string; pct: number; colorClass: string }) {
  const p = Math.min(100, Math.max(0, pct));
  return (
    <div className="mb-3">
      <div className="flex justify-between text-xs text-gray-600 dark:text-gray-400 mb-1">
        <span>{label}</span>
        <span>{p.toFixed(0)}%</span>
      </div>
      <div className="h-2.5 rounded-full bg-gray-200 dark:bg-gray-700 overflow-hidden">
        <div className={`h-full rounded-full transition-all ${colorClass}`} style={{ width: `${p}%` }} />
      </div>
    </div>
  );
}

function TaskDonut({
  pct,
  completed,
  inProgress,
  open,
}: {
  pct: number;
  completed: number;
  inProgress: number;
  open: number;
}) {
  const total = completed + inProgress + open || 1;
  const c = (completed / total) * 100;
  const ip = (inProgress / total) * 100;
  const o = (open / total) * 100;
  const grad = `conic-gradient(rgb(37 99 235) 0% ${c}%, rgb(234 179 8) ${c}% ${c + ip}%, rgb(156 163 175) ${c + ip}% 100%)`;
  return (
    <div className="flex flex-col items-center">
      <div
        className="w-36 h-36 rounded-full flex items-center justify-center relative"
        style={{ background: grad }}
      >
        <div className="w-24 h-24 rounded-full bg-white dark:bg-gray-800 flex flex-col items-center justify-center text-center shadow-inner">
          <div className="text-xl font-bold text-gray-900 dark:text-white">{pct}%</div>
          <div className="text-[10px] text-gray-500 px-1">progress</div>
        </div>
      </div>
      <div className="mt-3 text-xs space-y-1 text-gray-600 dark:text-gray-400">
        <div>
          <span className="inline-block w-2 h-2 rounded-full bg-blue-600 mr-1" /> Done: {completed}
        </div>
        <div>
          <span className="inline-block w-2 h-2 rounded-full bg-yellow-500 mr-1" /> Active: {inProgress}
        </div>
        <div>
          <span className="inline-block w-2 h-2 rounded-full bg-gray-400 mr-1" /> Open: {open}
        </div>
      </div>
    </div>
  );
}

const ProjectManagementOverviewReport: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const projectKey = searchParams.get('project') || '';

  const [projectList, setProjectList] = useState<Pick<Project, 'name' | 'project_name'>[]>([]);
  const [project, setProject] = useState<Project | null>(null);
  const [tasks, setTasks] = useState<TaskRow[]>([]);
  const [issues, setIssues] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const { data } = await projectService.getProjects({ limit_page_length: 500, order_by: 'modified desc' });
        if (!cancelled) setProjectList(data.map(p => ({ name: p.name, project_name: p.project_name })));
      } catch {
        if (!cancelled) setProjectList([]);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  const loadProjectBundle = useCallback(async (name: string) => {
    if (!name) {
      setProject(null);
      setTasks([]);
      setIssues([]);
      return;
    }
    setLoading(true);
    try {
      const [p, tk, iss] = await Promise.all([
        projectService.getProject(name),
        projectService.getTasksForProject(name, { limit: 300 }),
        projectService.getIssuesForProject(name, 100),
      ]);
      setProject(p);
      setTasks(tk);
      setIssues(iss);
    } catch {
      setProject(null);
      setTasks([]);
      setIssues([]);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadProjectBundle(projectKey);
  }, [projectKey, loadProjectBundle]);

  const onSelectProject = (name: string) => {
    setSearchParams(name ? { project: name } : {});
  };

  const today = new Date().toISOString().slice(0, 10);
  const elapsedPct = useMemo(() => {
    if (!project?.expected_start_date || !project?.expected_end_date) return 0;
    const total = daysBetween(project.expected_start_date, project.expected_end_date) || 1;
    const done = daysBetween(project.expected_start_date, today) ?? 0;
    return Math.min(100, Math.round((done / total) * 100));
  }, [project, today]);

  const budgetEstimate = project?.estimated_costing ?? project?.total_sales_amount ?? 0;
  const salesOrBill = project?.total_sales_amount ?? project?.total_billed_amount ?? 0;
  const spendPct =
    budgetEstimate > 0 ? Math.min(100, Math.round(((project?.total_costing_amount || 0) / budgetEstimate) * 100)) : 0;
  const salesPct = budgetEstimate > 0 ? Math.min(100, Math.round((salesOrBill / budgetEstimate) * 100)) : 0;

  const taskStats = useMemo(() => {
    let completed = 0;
    let inProgress = 0;
    let open = 0;
    for (const tk of tasks) {
      const s = (tk.status || '').toLowerCase();
      if (s.includes('complet') || s.includes('closed') || s.includes('cancel')) completed += 1;
      else if (s.includes('progress') || s.includes('working')) inProgress += 1;
      else open += 1;
    }
    const docPct = project?.percent_complete ?? 0;
    const mixPct = tasks.length ? Math.round((completed / tasks.length) * 100) : docPct;
    return { completed, inProgress, open, mixPct };
  }, [tasks, project?.percent_complete]);

  const issueByPri = useMemo(() => {
    const m: Record<string, number> = { High: 0, Medium: 0, Low: 0 };
    for (const i of issues) {
      const p = i.priority || 'Low';
      if (p in m) m[p] += 1;
      else m.Low += 1;
    }
    return m;
  }, [issues]);

  const openIssues = issues.filter(i => {
    const s = (i.status || '').toLowerCase();
    return !s.includes('closed') && !s.includes('resolved');
  });

  const lastWeekTasks = useMemo(() => {
    const cutoff = new Date();
    cutoff.setDate(cutoff.getDate() - 7);
    return tasks.filter(tk => {
      if (!tk.modified) return false;
      return new Date(tk.modified) >= cutoff;
    });
  }, [tasks]);

  const upcomingTasks = useMemo(() => {
    return tasks
      .filter(tk => tk.exp_start_date && new Date(tk.exp_start_date) >= new Date(today))
      .sort((a, b) => (a.exp_start_date || '').localeCompare(b.exp_start_date || ''))
      .slice(0, 8);
  }, [tasks, today]);

  return (
    <div className="p-6 max-w-7xl mx-auto space-y-6">
      <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
        <div className="flex items-center gap-3">
          <button
            type="button"
            onClick={() => navigate('/projects')}
            className="p-2 rounded-lg border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800"
          >
            <FaArrowLeft />
          </button>
          <div className="w-12 h-12 rounded-xl bg-teal-600 flex items-center justify-center">
            <FaFolderOpen className="text-white text-xl" />
          </div>
          <div>
            <h1 className="text-xl font-bold text-gray-900 dark:text-white">
              {t('projects.overviewReport', 'Project overview')}
            </h1>
            <p className="text-xs text-gray-500 dark:text-gray-400">
              {t('projects.overviewReportSub', 'Budget, tasks, issues & weekly status')}
            </p>
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <select
            value={projectKey}
            onChange={e => onSelectProject(e.target.value)}
            className="min-w-[220px] px-3 py-2 text-sm border rounded-lg dark:bg-gray-800 dark:border-gray-600"
          >
            <option value="">{t('projects.pickProject', 'Select a project…')}</option>
            {projectList.map(p => (
              <option key={p.name} value={p.name}>
                {p.project_name || p.name}
              </option>
            ))}
          </select>
          <button
            type="button"
            onClick={() => loadProjectBundle(projectKey)}
            className="p-2 rounded-lg border border-gray-200 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-800"
            title="Refresh"
          >
            <FaSync className={loading ? 'animate-spin' : ''} />
          </button>
        </div>
      </div>

      {!projectKey && (
        <div className="rounded-xl border border-dashed border-gray-300 dark:border-gray-600 p-10 text-center text-gray-500">
          {t('projects.selectToView', 'Choose a project to view the dashboard.')}
        </div>
      )}

      {projectKey && loading && (
        <div className="text-center py-16 text-gray-500">{t('common.loading', 'Loading…')}</div>
      )}

      {projectKey && !loading && project && (
        <>
          <div className="grid grid-cols-1 xl:grid-cols-4 gap-4">
            <div className="xl:col-span-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4 shadow-sm">
              <h2 className="text-sm font-semibold text-teal-800 dark:text-teal-200 mb-2">{project.project_name}</h2>
              <div className="flex flex-wrap gap-4 text-xs text-gray-600 dark:text-gray-400">
                <span>
                  {t('projects.start', 'Start')}: {formatDate(project.expected_start_date)}
                </span>
                <span>
                  {t('projects.end', 'End')}: {formatDate(project.expected_end_date)}
                </span>
                <span>ID: {project.name}</span>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
                <MiniBar label={t('projects.timelineElapsed', 'Timeline elapsed (to today)')} pct={elapsedPct} colorClass="bg-teal-500" />
                <MiniBar
                  label={t('projects.docProgress', 'Documented % complete')}
                  pct={project.percent_complete ?? 0}
                  colorClass="bg-indigo-500"
                />
              </div>
            </div>
          </div>

          <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-200 uppercase tracking-wide">
            {t('projects.weeklyStatus', 'Weekly project status')}
          </h3>

          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
            <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4 shadow-sm">
              <h4 className="text-xs font-bold text-gray-500 uppercase mb-2">Budget / sales</h4>
              <MiniBar label={t('projects.relativeCosting', 'Costs vs estimate')} pct={spendPct} colorClass="bg-blue-700" />
              <MiniBar label={t('projects.relativeBilling', 'Sales vs estimate')} pct={salesPct} colorClass="bg-sky-400" />
              <p className="text-[11px] text-gray-500 mt-2">
                Est.: {budgetEstimate ? budgetEstimate.toLocaleString() : '—'} · Sales:{' '}
                {salesOrBill ? salesOrBill.toLocaleString() : '—'}
              </p>
            </div>

            <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4 shadow-sm flex flex-col items-center">
              <h4 className="text-xs font-bold text-gray-500 uppercase mb-2 w-full text-left">Tasks</h4>
              <TaskDonut
                pct={taskStats.mixPct}
                completed={taskStats.completed}
                inProgress={taskStats.inProgress}
                open={taskStats.open}
              />
            </div>

            <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4 shadow-sm">
              <h4 className="text-xs font-bold text-gray-500 uppercase mb-2 flex items-center gap-1">
                <FaExclamationTriangle className="text-amber-500" /> Issues (priority)
              </h4>
              <MiniBar label="High" pct={openIssues.length ? (issueByPri.High / openIssues.length) * 100 : 0} colorClass="bg-red-500" />
              <MiniBar
                label="Medium"
                pct={openIssues.length ? (issueByPri.Medium / openIssues.length) * 100 : 0}
                colorClass="bg-amber-500"
              />
              <MiniBar label="Low" pct={openIssues.length ? (issueByPri.Low / openIssues.length) * 100 : 0} colorClass="bg-green-500" />
              <p className="text-[11px] text-gray-500 mt-2">Open issues: {openIssues.length}</p>
            </div>

            <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4 shadow-sm">
              <h4 className="text-xs font-bold text-gray-500 uppercase mb-2 flex items-center gap-1">
                <FaTasks /> Summary
              </h4>
              <ul className="text-xs text-gray-600 dark:text-gray-400 space-y-2 list-disc pl-4">
                <li>
                  Tasks: {tasks.length} · Issues: {issues.length}
                </li>
                <li>{project.notes ? String(project.notes).slice(0, 200) : '—'}</li>
              </ul>
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
            <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden shadow-sm">
              <div className="bg-violet-100 dark:bg-violet-900/40 px-3 py-2 text-xs font-semibold text-violet-900 dark:text-violet-100">
                Last 7 days — tasks touched
              </div>
              <table className="min-w-full text-xs">
                <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
                  {lastWeekTasks.length === 0 ? (
                    <tr>
                      <td className="px-3 py-4 text-gray-400">None</td>
                    </tr>
                  ) : (
                    lastWeekTasks.map((tk, i) => (
                      <tr key={tk.name}>
                        <td className="px-3 py-2">{i + 1}</td>
                        <td className="px-3 py-2">{tk.subject}</td>
                        <td className="px-3 py-2 text-gray-500">{tk.status}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>

            <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden shadow-sm">
              <div className="bg-violet-100 dark:bg-violet-900/40 px-3 py-2 text-xs font-semibold text-violet-900 dark:text-violet-100">
                Upcoming (by start date)
              </div>
              <table className="min-w-full text-xs">
                <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
                  {upcomingTasks.length === 0 ? (
                    <tr>
                      <td className="px-3 py-4 text-gray-400">None</td>
                    </tr>
                  ) : (
                    upcomingTasks.map((tk, i) => (
                      <tr key={tk.name}>
                        <td className="px-3 py-2">{i + 1}</td>
                        <td className="px-3 py-2">{tk.subject}</td>
                        <td className="px-3 py-2 text-gray-500">{formatDate(tk.exp_start_date)}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>

            <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden shadow-sm">
              <div className="bg-violet-100 dark:bg-violet-900/40 px-3 py-2 text-xs font-semibold text-violet-900 dark:text-violet-100">
                Open issues
              </div>
              <table className="min-w-full text-xs">
                <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
                  {openIssues.length === 0 ? (
                    <tr>
                      <td className="px-3 py-4 text-gray-400">None</td>
                    </tr>
                  ) : (
                    openIssues.slice(0, 10).map((iss, i) => (
                      <tr key={iss.name}>
                        <td className="px-3 py-2">{i + 1}</td>
                        <td className="px-3 py-2">{iss.subject}</td>
                        <td className="px-3 py-2 text-gray-500">{iss.priority}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </>
      )}
    </div>
  );
};

export default ProjectManagementOverviewReport;
