import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
  FaArrowLeft, FaSave, FaEdit, FaTimes, FaPlus, FaTrash,
  FaCheckCircle, FaTimesCircle, FaSpinner, FaInfoCircle,
} from 'react-icons/fa';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { useProjectTemplateDetails, useProjectMutations } from '../hooks/useProject';
import LinkField from '../components/LinkField';
import ActivityLog from '../components/ActivityLog';
import type { ProjectTemplate, ProjectTemplateTask } from '../services/projectService';

// Confirmed from Frappe desk: Project Template Task uses `task` (Link to Task, is_template=1)
// and `subject` is auto-fetched from the linked task. `duration` is in days.

const emptyTask = (): ProjectTemplateTask => ({
  task: '',
  subject: '',
  duration: undefined,
});

/** Only keep rows that have a task selected; strip empty/undefined fields */
const sanitizeTemplateTasks = (tasks: ProjectTemplateTask[]): ProjectTemplateTask[] =>
  tasks
    .filter(t => t.task?.trim())
    .map(({ task, duration }) => ({
      task: task!.trim(),
      ...(duration !== undefined ? { duration } : {}),
    }));

const ProjectTemplateDetail: React.FC = () => {
  const { t } = useTranslation();
  const { templateName } = useParams<{ templateName: string }>();
  const navigate = useNavigate();
  const isNew = templateName === 'new';

  const { template, loading, error, refetch } = useProjectTemplateDetails(isNew ? null : (templateName || null));
  const { createProjectTemplate, updateProjectTemplate, loading: saving } = useProjectMutations();
  const [isEditing, setIsEditing] = useState(isNew);

  const [form, setForm] = useState<Partial<ProjectTemplate>>({
    name: '',
    project_type: '',
    tasks: [emptyTask()],
  });

  useEffect(() => {
    if (template && !isNew) {
      setForm({
        name: template.name || '',
        project_type: template.project_type || '',
        tasks: template.tasks?.length ? template.tasks : [],
      });
    }
  }, [template, isNew]);

  const setField = (k: keyof ProjectTemplate, v: any) => setForm(f => ({ ...f, [k]: v }));

  const addTask = () => setForm(f => ({
    ...f,
    tasks: [...(f.tasks || []), emptyTask()],
  }));

  const updateTask = (idx: number, k: keyof ProjectTemplateTask, v: any) => setForm(f => {
    const tasks = [...(f.tasks || [])];
    tasks[idx] = { ...tasks[idx], [k]: v };
    return { ...f, tasks };
  });

  const removeTask = (idx: number) => setForm(f => {
    const tasks = [...(f.tasks || [])];
    tasks.splice(idx, 1);
    return { ...f, tasks };
  });

  const handleSave = async () => {
    if (!form.name?.trim()) { toast.error('Template name is required'); return; }

    const cleanTasks = sanitizeTemplateTasks(form.tasks || []);
    const payload: Partial<ProjectTemplate> = {
      name: form.name.trim(),
      // Only send project_type if non-empty — empty string causes Link validation errors
      ...(form.project_type?.trim() ? { project_type: form.project_type.trim() } : {}),
      tasks: cleanTasks,
    };

    try {
      if (isNew) {
        const created = await createProjectTemplate(payload);
        toast.success(t('projects.templateCreated'), { icon: <FaCheckCircle /> });
        navigate(`/projects/templates/${encodeURIComponent(created.name)}`);
      } else {
        await updateProjectTemplate(templateName!, payload);
        toast.success(t('projects.templateUpdated'), { icon: <FaCheckCircle /> });
        setIsEditing(false);
        refetch();
      }
    } catch (err) {
      toast.error(err instanceof Error ? err.message : t('common.error'), { icon: <FaTimesCircle /> });
    }
  };

  const inputCls = (ed: boolean) =>
    `w-full px-3 py-2 text-sm border rounded-lg ${ed
      ? 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-400'
      : 'border-transparent bg-gray-50 dark:bg-gray-800 text-gray-800 dark:text-gray-200 cursor-default'}`;

  const editable = isNew || isEditing;

  if (loading) return <div className="flex items-center justify-center min-h-[400px]"><FaSpinner className="animate-spin text-purple-500 text-3xl" /></div>;

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 px-6 py-6">
      <ToastContainer position="top-right" autoClose={3500} />

      {/* Breadcrumb */}
      <div className="flex items-center gap-2 text-sm mb-6">
        <button onClick={() => navigate('/projects')} className="text-gray-500 hover:text-indigo-600 dark:text-gray-400">{t('projects.moduleTitle')}</button>
        <span className="text-gray-400">/</span>
        <button onClick={() => navigate('/projects/templates')} className="text-gray-500 hover:text-purple-600 dark:text-gray-400">{t('projects.projectTemplateDoctype')}</button>
        <span className="text-gray-400">/</span>
        <span className="text-gray-700 dark:text-gray-300">{isNew ? t('projects.newProjectTemplate') : templateName}</span>
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm overflow-hidden">
        {/* Header */}
        <div className="px-6 py-4 border-b border-gray-100 dark:border-gray-700 flex items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <button onClick={() => navigate('/projects/templates')} className="text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"><FaArrowLeft /></button>
            <h1 className="text-xl font-bold text-gray-900 dark:text-white">
              {isNew ? t('projects.newProjectTemplate') : (form.name || templateName)}
            </h1>
          </div>
          <div className="flex gap-2">
            {!isNew && !isEditing && (
              <button onClick={() => setIsEditing(true)} className="flex items-center gap-2 px-4 py-2 border border-purple-500 text-purple-600 dark:text-purple-400 rounded-lg hover:bg-purple-50 dark:hover:bg-purple-900/20 text-sm">
                <FaEdit /> {t('common.edit')}
              </button>
            )}
            {editable && (
              <>
                <button onClick={handleSave} disabled={saving} className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 text-sm">
                  {saving ? <FaSpinner className="animate-spin" /> : <FaSave />}
                  {saving ? t('common.saving') : t('common.save')}
                </button>
                {!isNew && (
                  <button onClick={() => setIsEditing(false)} className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-sm"><FaTimes /></button>
                )}
              </>
            )}
          </div>
        </div>

        {error && !isNew && (
          <div className="mx-6 mt-4 p-3 bg-red-50 dark:bg-red-900/20 rounded text-red-700 dark:text-red-300 text-sm">{error}</div>
        )}

        {/* Header fields */}
        <div className="p-6 grid grid-cols-1 sm:grid-cols-2 gap-4 border-b border-gray-100 dark:border-gray-700">
          <div>
            <label className="block text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wide mb-1">Name *</label>
            <input
              type="text"
              value={form.name || ''}
              onChange={e => setField('name', e.target.value)}
              disabled={!isNew}
              className={inputCls(isNew)}
              placeholder="Template name..."
            />
            {!isNew && <p className="text-xs text-gray-400 mt-1">Name cannot be changed after creation</p>}
          </div>
          <div>
            <label className="block text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wide mb-1">Project Type</label>
            {editable
              ? <LinkField label="Project Type" hideLabel value={form.project_type || ''} onChange={v => setField('project_type', v)} doctype="Project Type" placeholder="Select project type..." />
              : <div className="px-3 py-2 text-sm text-gray-800 dark:text-gray-200">{form.project_type || '-'}</div>}
          </div>
        </div>

        {/* Tasks child table */}
        <div className="p-6">
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wide">Tasks</h3>
            {editable && (
              <button onClick={addTask} className="flex items-center gap-1.5 px-3 py-1.5 bg-purple-600 text-white text-xs rounded-lg hover:bg-purple-700">
                <FaPlus /> Add Row
              </button>
            )}
          </div>

          {/* Info banner */}
          <div className="flex items-start gap-2 mb-3 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800 text-xs text-blue-700 dark:text-blue-300">
            <FaInfoCircle className="mt-0.5 flex-shrink-0" />
            <span>
              Each row links to a <strong>Task</strong> that has <strong>Is Template = Yes</strong>.
              To create a new template task, first go to{' '}
              <button onClick={() => navigate('/projects/tasks/new')} className="underline hover:text-blue-900 dark:hover:text-blue-100">Tasks → New Task</button>
              {' '}and check "Is Template", then come back and select it here.
            </span>
          </div>

          {(form.tasks || []).length === 0 ? (
            <div className="py-8 text-center text-gray-400 dark:text-gray-500 text-sm bg-gray-50 dark:bg-gray-900/30 rounded-lg border border-dashed border-gray-300 dark:border-gray-600">
              {editable ? 'Click "Add Row" to link template tasks' : 'No tasks defined'}
            </div>
          ) : (
            <div className="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-700">
              <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700 text-sm">
                <thead className="bg-gray-50 dark:bg-gray-900/50">
                  <tr>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase w-10">No.</th>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase min-w-[280px]">Task * <span className="font-normal normal-case text-gray-400">(is_template=Yes)</span></th>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Subject</th>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase w-28">Duration (days)</th>
                    {editable && <th className="px-3 py-2 w-10" />}
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                  {(form.tasks || []).map((task, idx) => (
                    <tr key={idx}>
                      <td className="px-3 py-2 text-gray-500 text-xs font-medium">{idx + 1}</td>

                      {/* task — Link to Task (is_template=1) */}
                      <td className="px-2 py-1.5 min-w-[280px]">
                        {editable
                          ? <LinkField
                              label="Task"
                              hideLabel
                              value={task.task || ''}
                              onChange={v => updateTask(idx, 'task', v)}
                              doctype="Task"
                              placeholder="Search template task..."
                              compact
                            />
                          : <span className="text-gray-800 dark:text-gray-200 font-medium">{task.task || '-'}</span>}
                      </td>

                      {/* subject — auto-fetched from linked task, read-only */}
                      <td className="px-3 py-2">
                        <span className="text-gray-600 dark:text-gray-400 text-xs italic">
                          {task.subject || '(from task)'}
                        </span>
                      </td>

                      {/* duration in days */}
                      <td className="px-2 py-1.5">
                        {editable
                          ? <input
                              type="number" min={0}
                              value={task.duration ?? ''}
                              onChange={e => updateTask(idx, 'duration', e.target.value ? parseInt(e.target.value) : undefined)}
                              placeholder="0"
                              className="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-1 focus:ring-purple-400"
                            />
                          : <span className="text-gray-700 dark:text-gray-300 text-sm">{task.duration ?? '-'}</span>}
                      </td>

                      {editable && (
                        <td className="px-3 py-2">
                          <button onClick={() => removeTask(idx)} className="text-red-500 hover:text-red-700 p-1 rounded hover:bg-red-50 dark:hover:bg-red-900/20">
                            <FaTrash size={12} />
                          </button>
                        </td>
                      )}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {/* Meta */}
          {!isNew && template && (
            <div className="mt-6 pt-4 border-t border-gray-100 dark:border-gray-700 grid grid-cols-2 gap-3 text-xs text-gray-500 dark:text-gray-400">
              <div><span className="font-medium block">Created</span>{template.creation ? new Date(template.creation).toLocaleString() : '-'}</div>
              <div><span className="font-medium block">Modified</span>{template.modified ? new Date(template.modified).toLocaleString() : '-'}</div>
            </div>
          )}

          {!isNew && (
            <div className="mt-4">
              <ActivityLog
                doctype="Project Template"
                docname={template?.name || templateName || ''}
                creationDate={template?.creation}
                createdBy={template?.owner}
                compact={false}
                initialVisible={5}
                collapsible
                startCollapsed
              />
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default ProjectTemplateDetail;
