import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useParams, useNavigate, useSearchParams, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { FaArrowLeft, FaSave, FaEdit, FaChartPie } from 'react-icons/fa';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import projectService, { type Project } from '../services/projectService';
import LinkField from '../components/LinkField';
import ProjectSalesAndCustomerPanel from '../components/ProjectSalesAndCustomerPanel';

type FormState = {
  project_name: string;
  status: string;
  priority: string;
  customer: string;
  customer_name: string;
  company: string;
  expected_start_date: string;
  expected_end_date: string;
  percent_complete: number | '';
  notes: string;
  sales_order: string;
};

const emptyForm = (): FormState => ({
  project_name: '',
  status: 'Open',
  priority: 'Medium',
  customer: '',
  customer_name: '',
  company: '',
  expected_start_date: '',
  expected_end_date: '',
  percent_complete: '',
  notes: '',
  sales_order: '',
});

const ProjectDetail: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const location = useLocation();
  const [searchParams] = useSearchParams();
  const { projectName: rawName } = useParams<{ projectName: string }>();

  const projectName = useMemo(() => {
    if (rawName === 'new') return 'new';
    const prefix = '/projects/list/';
    let path = window.location.pathname;
    if (path.startsWith('/asm_app')) path = path.slice('/asm_app'.length) || '/';
    const idx = path.indexOf(prefix);
    if (idx !== -1) {
      const encoded = path.slice(idx + prefix.length);
      try {
        return decodeURIComponent(encoded);
      } catch {
        return encoded;
      }
    }
    return rawName ? decodeURIComponent(rawName) : '';
  }, [rawName, location.pathname]);

  const isNew = projectName === 'new';
  const prefillCustomer = searchParams.get('customer') || '';
  const prefillSalesOrder = searchParams.get('sales_order') || '';

  const [loading, setLoading] = useState(!isNew);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState<FormState>(() => emptyForm());
  const [isEditing, setIsEditing] = useState(isNew || searchParams.get('edit') === '1');

  const load = useCallback(async () => {
    if (!projectName || isNew) return;
    setLoading(true);
    try {
      const p: Project = await projectService.getProject(projectName);
      setForm({
        project_name: p.project_name || '',
        status: p.status || 'Open',
        priority: p.priority || '',
        customer: p.customer || '',
        customer_name: p.customer_name || '',
        company: p.company || '',
        expected_start_date: (p.expected_start_date || '').split(' ')[0],
        expected_end_date: (p.expected_end_date || '').split(' ')[0],
        percent_complete: typeof p.percent_complete === 'number' ? p.percent_complete : '',
        notes: p.notes || '',
        sales_order: (p as any).sales_order || '',
      });
    } catch (e: any) {
      toast.error(e.message || 'Failed to load project');
      navigate('/projects/list');
    } finally {
      setLoading(false);
    }
  }, [projectName, isNew, navigate]);

  useEffect(() => {
    load();
  }, [load]);

  useEffect(() => {
    if (isNew && (prefillCustomer || prefillSalesOrder)) {
      setForm(prev => ({
        ...prev,
        customer: prefillCustomer || prev.customer,
        sales_order: prefillSalesOrder || prev.sales_order,
      }));
    }
  }, [isNew, prefillCustomer, prefillSalesOrder]);

  useEffect(() => {
    if (!isNew && searchParams.get('edit') === '1') setIsEditing(true);
  }, [isNew, searchParams]);

  const setField = (name: keyof FormState, value: string | number) => {
    setForm(prev => ({ ...prev, [name]: value }));
  };

  const payloadFromForm = (): Record<string, any> => {
    const o: Record<string, any> = {
      project_name: form.project_name.trim(),
      status: form.status,
      priority: form.priority || undefined,
      customer: form.customer || undefined,
      company: form.company || undefined,
      expected_start_date: form.expected_start_date || undefined,
      expected_end_date: form.expected_end_date || undefined,
      notes: form.notes || undefined,
    };
    if (form.percent_complete !== '' && form.percent_complete != null) {
      o.percent_complete = Number(form.percent_complete);
    }
    if (form.sales_order.trim()) o.sales_order = form.sales_order.trim();
    return o;
  };

  const handleSave = async () => {
    if (!form.project_name.trim()) {
      toast.error(t('projects.projectNameRequired', 'Project name is required'));
      return;
    }
    setSaving(true);
    try {
      if (isNew) {
        const created = await projectService.createProject(payloadFromForm());
        toast.success(t('projects.created', 'Project created'));
        navigate(`/projects/list/${encodeURIComponent(created.name)}`, { replace: true });
      } else {
        await projectService.updateProject(projectName, payloadFromForm());
        toast.success(t('projects.updated', 'Project updated'));
        setIsEditing(false);
        await load();
      }
    } catch (e: any) {
      toast.error(e.message || 'Save failed');
    } finally {
      setSaving(false);
    }
  };

  const disabled = !isEditing;

  if (loading && !isNew) {
    return (
      <div className="flex items-center justify-center min-h-[40vh] text-gray-500 dark:text-gray-400">
        Loading…
      </div>
    );
  }

  return (
    <div className="p-6 max-w-4xl mx-auto">
      <ToastContainer position="top-right" autoClose={3000} />

      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div className="flex items-center gap-3">
          <button
            type="button"
            onClick={() => navigate('/projects/list')}
            className="p-2 rounded-lg border border-gray-200 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-800"
          >
            <FaArrowLeft />
          </button>
          <div>
            <h1 className="text-xl font-bold text-gray-900 dark:text-white">
              {isNew ? t('projects.newProject', 'New project') : form.project_name || projectName}
            </h1>
            {!isNew && <p className="text-xs text-gray-500 font-mono">{projectName}</p>}
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          {!isNew && (
            <button
              type="button"
              onClick={() => navigate(`/projects/overview?project=${encodeURIComponent(projectName)}`)}
              className="inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-teal-300 dark:border-teal-700 text-teal-800 dark:text-teal-200 text-sm font-medium hover:bg-teal-50 dark:hover:bg-teal-900/20"
            >
              <FaChartPie size={14} /> {t('projects.overviewReport', 'Project overview')}
            </button>
          )}
          {!isNew && !isEditing && (
            <button
              type="button"
              onClick={() => setIsEditing(true)}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-900 dark:text-white text-sm font-semibold"
            >
              <FaEdit size={14} /> {t('listPages.edit', 'Edit')}
            </button>
          )}
          {isEditing && (
            <button
              type="button"
              disabled={saving}
              onClick={handleSave}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold disabled:opacity-50"
            >
              <FaSave size={14} /> {saving ? '…' : t('common.save', 'Save')}
            </button>
          )}
        </div>
      </div>

      <ProjectSalesAndCustomerPanel
        projectName={isNew ? undefined : projectName}
        isNew={isNew}
        customer={form.customer}
        customerName={form.customer_name}
        salesOrder={form.sales_order}
        prefillCustomer={prefillCustomer}
        prefillSalesOrder={prefillSalesOrder}
      />

      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5 space-y-4 shadow-sm">
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div>
            <label className="block text-[10px] font-semibold text-gray-500 uppercase mb-1">
              {t('projects.projectName', 'Project name')} *
            </label>
            <input
              name="project_name"
              value={form.project_name}
              onChange={e => setField('project_name', e.target.value)}
              disabled={disabled}
              className="w-full px-3 py-2 text-sm border rounded-lg dark:bg-gray-700 dark:border-gray-600 disabled:opacity-60"
            />
          </div>
          <div className="grid grid-cols-2 gap-2">
            <div>
              <label className="block text-[10px] font-semibold text-gray-500 uppercase mb-1">Status</label>
              <select
                value={form.status}
                onChange={e => setField('status', e.target.value)}
                disabled={disabled}
                className="w-full px-3 py-2 text-sm border rounded-lg dark:bg-gray-700 dark:border-gray-600 disabled:opacity-60"
              >
                <option value="Open">Open</option>
                <option value="Completed">Completed</option>
                <option value="Cancelled">Cancelled</option>
              </select>
            </div>
            <div>
              <label className="block text-[10px] font-semibold text-gray-500 uppercase mb-1">Priority</label>
              <select
                value={form.priority}
                onChange={e => setField('priority', e.target.value)}
                disabled={disabled}
                className="w-full px-3 py-2 text-sm border rounded-lg dark:bg-gray-700 dark:border-gray-600 disabled:opacity-60"
              >
                <option value="">—</option>
                <option value="High">High</option>
                <option value="Medium">Medium</option>
                <option value="Low">Low</option>
              </select>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <LinkField
            label={t('projects.customer', 'Customer')}
            doctype="Customer"
            value={form.customer}
            onChange={v => setField('customer', v)}
            disabled={disabled}
            compact
          />
          <LinkField
            label={t('projects.company', 'Company')}
            doctype="Company"
            value={form.company}
            onChange={v => setField('company', v)}
            disabled={disabled}
            compact
          />
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <div>
            <label className="block text-[10px] font-semibold text-gray-500 uppercase mb-1">Start</label>
            <input
              type="date"
              value={form.expected_start_date}
              onChange={e => setField('expected_start_date', e.target.value)}
              disabled={disabled}
              className="w-full px-3 py-2 text-sm border rounded-lg dark:bg-gray-700 dark:border-gray-600 disabled:opacity-60"
            />
          </div>
          <div>
            <label className="block text-[10px] font-semibold text-gray-500 uppercase mb-1">End</label>
            <input
              type="date"
              value={form.expected_end_date}
              onChange={e => setField('expected_end_date', e.target.value)}
              disabled={disabled}
              className="w-full px-3 py-2 text-sm border rounded-lg dark:bg-gray-700 dark:border-gray-600 disabled:opacity-60"
            />
          </div>
          <div>
            <label className="block text-[10px] font-semibold text-gray-500 uppercase mb-1">% Complete</label>
            <input
              type="number"
              min={0}
              max={100}
              value={form.percent_complete}
              onChange={e => setField('percent_complete', e.target.value === '' ? '' : Number(e.target.value))}
              disabled={disabled}
              className="w-full px-3 py-2 text-sm border rounded-lg dark:bg-gray-700 dark:border-gray-600 disabled:opacity-60"
            />
          </div>
        </div>

        <LinkField
          label={`${t('projects.salesOrder', 'Sales Order')} (${t('projects.optional', 'optional')})`}
          doctype="Sales Order"
          value={form.sales_order}
          onChange={v => setField('sales_order', v)}
          disabled={disabled}
          compact
        />

        <div>
          <label className="block text-[10px] font-semibold text-gray-500 uppercase mb-1">Notes</label>
          <textarea
            value={form.notes}
            onChange={e => setField('notes', e.target.value)}
            disabled={disabled}
            rows={4}
            className="w-full px-3 py-2 text-sm border rounded-lg dark:bg-gray-700 dark:border-gray-600 disabled:opacity-60"
          />
        </div>
      </div>
    </div>
  );
};

export default ProjectDetail;
