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

// Frappe Activity Type:
//   autoname = "field:activity_type"  →  name column = activity_type value
//   Fields: activity_type (Data, mandatory), billing_rate (Currency), costing_rate (Currency), disabled (Check)

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

  const { activityType, loading, error, refetch } = useActivityTypeDetails(isNew ? null : (activityTypeName || null));
  const { createActivityType, updateActivityType, loading: saving } = useProjectMutations();
  const [isEditing, setIsEditing] = useState(isNew);

  const [form, setForm] = useState<Partial<ActivityType>>({
    activity_type: '',
    billing_rate: undefined,
    costing_rate: undefined,
    disabled: 0,
  });

  useEffect(() => {
    if (activityType && !isNew) {
      setForm({
        activity_type: activityType.activity_type || activityType.name || '',
        billing_rate: activityType.billing_rate,
        costing_rate: activityType.costing_rate,
        disabled: activityType.disabled ?? 0,
      });
    }
  }, [activityType, isNew]);

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

  const handleSave = async () => {
    if (!form.activity_type?.trim()) { toast.error('Activity Type name is required'); return; }
    try {
      if (isNew) {
        // Frappe uses autoname = "field:activity_type" — send activity_type field
        // Frappe auto-sets name = activity_type value
        const payload: Partial<ActivityType> = {
          activity_type: form.activity_type!.trim(),
          ...(form.billing_rate !== undefined ? { billing_rate: form.billing_rate } : {}),
          ...(form.costing_rate !== undefined ? { costing_rate: form.costing_rate } : {}),
          disabled: form.disabled ?? 0,
        };
        const created = await createActivityType(payload);
        toast.success('Activity Type created', { icon: <FaCheckCircle /> });
        navigate(`/projects/activity-types/${encodeURIComponent(created.name)}`);
      } else {
        // For update, only send mutable fields (not activity_type/name which can't change)
        const payload: Partial<ActivityType> = {
          ...(form.billing_rate !== undefined ? { billing_rate: form.billing_rate } : {}),
          ...(form.costing_rate !== undefined ? { costing_rate: form.costing_rate } : {}),
          disabled: form.disabled ?? 0,
        };
        await updateActivityType(activityTypeName!, payload);
        toast.success('Activity Type updated', { icon: <FaCheckCircle /> });
        setIsEditing(false);
        refetch();
      }
    } catch (err) {
      toast.error(err instanceof Error ? err.message : t('common.error'), { icon: <FaTimesCircle /> });
    }
  };

  const handleCancel = () => {
    setIsEditing(false);
    if (activityType) {
      setForm({
        activity_type: activityType.activity_type || activityType.name || '',
        billing_rate: activityType.billing_rate,
        costing_rate: activityType.costing_rate,
        disabled: activityType.disabled ?? 0,
      });
    }
  };

  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-teal-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-teal-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/activity-types')} className="text-gray-500 hover:text-teal-600 dark:text-gray-400">{t('projects.activityTypeDoctype')}</button>
        <span className="text-gray-400">/</span>
        <span className="text-gray-700 dark:text-gray-300">{isNew ? t('projects.newActivityType') : (activityType?.activity_type || activityType?.name || activityTypeName)}</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/activity-types')} 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.newActivityType') : (form.activity_type || activityTypeName)}
            </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-teal-500 text-teal-600 dark:text-teal-400 rounded-lg hover:bg-teal-50 dark:hover:bg-teal-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-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50 text-sm">
                  {saving ? <FaSpinner className="animate-spin" /> : <FaSave />}
                  {saving ? t('common.saving') : t('common.save')}
                </button>
                {!isNew && (
                  <button onClick={handleCancel} className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-600 dark:text-gray-400 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>
        )}

        <div className="p-6 space-y-4">
          {/* Activity Type name → maps to `activity_type` field in Frappe */}
          <div>
            <label className="block text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wide mb-1">
              Activity Type *
              {isNew && <span className="ml-1 text-gray-400 font-normal normal-case text-xs">(becomes the record name)</span>}
            </label>
            <input
              type="text"
              value={form.activity_type || ''}
              onChange={e => set('activity_type', e.target.value)}
              disabled={!isNew}
              className={inputCls(isNew)}
              placeholder="e.g. Design, Development, Testing..."
            />
            {!isNew && <p className="text-xs text-gray-400 mt-1">Activity Type name cannot be changed after creation.</p>}
          </div>

          <div className="grid grid-cols-2 gap-4">
            {/* Billing Rate — standard Frappe field is `billing_rate` */}
            <div>
              <label className="block text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wide mb-1">Billing Rate</label>
              <input
                type="number" min={0} step={0.01}
                value={form.billing_rate ?? ''}
                onChange={e => set('billing_rate', e.target.value ? parseFloat(e.target.value) : undefined)}
                disabled={!editable}
                className={inputCls(editable)}
                placeholder="0.00"
              />
            </div>

            {/* Costing Rate — standard Frappe field is `costing_rate` */}
            <div>
              <label className="block text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wide mb-1">Costing Rate</label>
              <input
                type="number" min={0} step={0.01}
                value={form.costing_rate ?? ''}
                onChange={e => set('costing_rate', e.target.value ? parseFloat(e.target.value) : undefined)}
                disabled={!editable}
                className={inputCls(editable)}
                placeholder="0.00"
              />
            </div>
          </div>

          {/* Disabled */}
          <div>
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={!!form.disabled}
                onChange={e => set('disabled', e.target.checked ? 1 : 0)}
                disabled={!editable}
                className="w-4 h-4 text-red-500 rounded"
              />
              <span className="text-sm text-gray-700 dark:text-gray-300">Disabled</span>
            </label>
          </div>

          {/* Meta */}
          {!isNew && activityType && (
            <div className="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>{activityType.creation ? new Date(activityType.creation).toLocaleString() : '-'}</div>
              <div><span className="font-medium block">Modified</span>{activityType.modified ? new Date(activityType.modified).toLocaleString() : '-'}</div>
            </div>
          )}

          {!isNew && (
            <div className="pt-4">
              <ActivityLog
                doctype="Activity Type"
                docname={activityType?.name || activityTypeName || ''}
                creationDate={activityType?.creation}
                createdBy={activityType?.owner}
                compact={false}
                initialVisible={5}
                collapsible
                startCollapsed
              />
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default ActivityTypeDetail;
