import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  FaArrowLeft, FaSave, FaEdit, FaTimes,
  FaCheckCircle, FaTimesCircle, FaSpinner, FaUserFriends,
  FaChevronDown, FaChevronRight,
} from 'react-icons/fa';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import masterService, { Customer } from '../services/masterService';
import LinkField from '../components/LinkField';
import ActivityLog from '../components/ActivityLog';

// ─── Helpers ─────────────────────────────────────────────────────────────────
const FL: React.FC<{ children: React.ReactNode; required?: boolean }> = ({ children, required }) => (
  <label className="block text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1">
    {children}{required && <span className="text-red-500 ml-0.5">*</span>}
  </label>
);
const RV: React.FC<{ children?: React.ReactNode }> = ({ children }) => (
  <div className="px-3 py-2 text-sm text-gray-800 dark:text-gray-200 bg-gray-50 dark:bg-gray-800/60 rounded-lg min-h-[38px] flex items-center">
    {children || <span className="text-gray-400">-</span>}
  </div>
);
const inputCls = 'w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-cyan-400';

const CollapsibleSection: React.FC<{ title: string; children: React.ReactNode; defaultOpen?: boolean }> = ({ title, children, defaultOpen = true }) => {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div className="border-t border-gray-100 dark:border-gray-700">
      <button type="button" onClick={() => setOpen(o => !o)}
        className="w-full flex items-center justify-between px-6 py-3 hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors">
        <span className="text-sm font-semibold text-gray-700 dark:text-gray-300">{title}</span>
        {open ? <FaChevronDown className="text-gray-400 text-xs" /> : <FaChevronRight className="text-gray-400 text-xs" />}
      </button>
      {open && <div className="px-6 pb-5">{children}</div>}
    </div>
  );
};

const CUSTOMER_TYPES = ['Company', 'Individual', 'Hospital'];

// ─── Component ────────────────────────────────────────────────────────────────
const CustomerDetail: React.FC = () => {
  const { customerName } = useParams<{ customerName: string }>();
  const navigate = useNavigate();
  const isNew = customerName === 'new';

  const [customer, setCustomer] = useState<Customer | null>(null);
  const [loading, setLoading]   = useState(!isNew);
  const [saving, setSaving]     = useState(false);
  const [isEditing, setIsEditing] = useState(isNew);
  const [error, setError]         = useState('');

  const emptyForm: Partial<Customer> = {
    customer_name: '', customer_type: 'Company', customer_group: 'All Customer Groups',
    territory: 'All Territories', language: 'en',
    is_internal_customer: 0, default_commission_rate: 0,
    so_required: 0, dn_required: 0, is_frozen: 0, disabled: 0,
  };
  const [form, setForm] = useState<Partial<Customer>>(emptyForm);

  const syncForm = useCallback((c: Customer) => {
    setForm({
      customer_name:           c.customer_name || '',
      customer_type:           c.customer_type || 'Company',
      customer_group:          c.customer_group || '',
      territory:               c.territory || '',
      language:                c.language || 'en',
      is_internal_customer:    c.is_internal_customer ?? 0,
      default_commission_rate: c.default_commission_rate ?? 0,
      so_required:             c.so_required ?? 0,
      dn_required:             c.dn_required ?? 0,
      is_frozen:               c.is_frozen ?? 0,
      disabled:                c.disabled ?? 0,
    });
  }, []);

  useEffect(() => {
    if (!isNew && customerName) {
      setLoading(true);
      masterService.getCustomer(customerName)
        .then(c => { setCustomer(c); syncForm(c); })
        .catch(e => setError(e.message))
        .finally(() => setLoading(false));
    }
  }, [customerName, isNew, syncForm]);

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

  const handleSave = async () => {
    if (!form.customer_name?.trim()) { toast.error('Customer Name is required'); return; }
    setSaving(true);
    try {
      if (isNew) {
        const created = await masterService.createCustomer(form);
        toast.success('Customer created', { icon: <FaCheckCircle /> });
        navigate(`/customers/${encodeURIComponent(created.name)}`);
      } else {
        const updated = await masterService.updateCustomer(customerName!, form);
        toast.success('Customer updated', { icon: <FaCheckCircle /> });
        setCustomer(updated); syncForm(updated); setIsEditing(false);
      }
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Save failed', { icon: <FaTimesCircle /> });
    } finally {
      setSaving(false);
    }
  };

  const handleCancel = () => { if (customer) syncForm(customer); setIsEditing(false); };
  const editable = isNew || isEditing;

  if (loading) return <div className="flex justify-center items-center min-h-[400px]"><FaSpinner className="animate-spin text-cyan-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 text-gray-500 dark:text-gray-400">
        <button onClick={() => navigate('/projects')} className="hover:text-cyan-600">Project Management</button>
        <span>/</span>
        <button onClick={() => navigate('/customers')} className="hover:text-cyan-600">Customers</button>
        <span>/</span>
        <span className="text-gray-700 dark:text-gray-300">{isNew ? 'New Customer' : customerName}</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 flex-wrap">
          <div className="flex items-center gap-3">
            <button onClick={() => navigate('/customers')} className="text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"><FaArrowLeft /></button>
            <div className="w-10 h-10 rounded-xl bg-cyan-600 flex items-center justify-center flex-shrink-0">
              <FaUserFriends className="text-white" />
            </div>
            <div>
              <h1 className="text-xl font-bold text-gray-900 dark:text-white">
                {isNew ? 'New Customer' : (customer?.customer_name || customerName)}
              </h1>
              {!isNew && customer && (
                <span className={`text-xs px-2 py-0.5 rounded font-medium ${customer.disabled ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'}`}>
                  {customer.disabled ? 'Disabled' : 'Active'}
                </span>
              )}
            </div>
          </div>
          <div className="flex gap-2">
            {!isNew && !isEditing && (
              <button onClick={() => setIsEditing(true)} className="flex items-center gap-2 px-4 py-2 bg-cyan-600 text-white rounded-lg hover:bg-cyan-700 text-sm">
                <FaEdit /> Edit
              </button>
            )}
            {editable && (
              <>
                <button onClick={handleSave} disabled={saving} className="flex items-center gap-2 px-4 py-2 bg-cyan-600 text-white rounded-lg hover:bg-cyan-700 disabled:opacity-50 text-sm font-medium">
                  {saving ? <FaSpinner className="animate-spin" /> : <FaSave />}
                  {saving ? 'Saving…' : '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 && <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>}

        {/* ── Main fields ── */}
        <div className="p-6 grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4 border-b border-gray-100 dark:border-gray-700">

          <div className="sm:col-span-2">
            <FL required>Customer Name</FL>
            {editable
              ? <input value={form.customer_name || ''} onChange={e => set('customer_name', e.target.value)} className={inputCls} placeholder="Enter customer name" />
              : <RV>{form.customer_name}</RV>}
          </div>

          <div>
            <FL>Customer Type</FL>
            {editable
              ? <select value={form.customer_type || 'Company'} onChange={e => set('customer_type', e.target.value)} className={inputCls}>
                  {CUSTOMER_TYPES.map(t => <option key={t}>{t}</option>)}
                </select>
              : <RV>{form.customer_type}</RV>}
          </div>

          <div>
            <FL>Territory</FL>
            {editable
              ? <LinkField label="Territory" hideLabel doctype="Territory" value={form.territory || ''} onChange={v => set('territory', v)} placeholder="Select territory…" />
              : <RV>{form.territory}</RV>}
          </div>

          <div>
            <FL>Customer Group</FL>
            {editable
              ? <LinkField label="Customer Group" hideLabel doctype="Customer Group" value={form.customer_group || ''} onChange={v => set('customer_group', v)} placeholder="Select group…" />
              : <RV>{form.customer_group}</RV>}
          </div>

          <div>
            <FL>Language</FL>
            {editable
              ? <LinkField label="Language" hideLabel doctype="Language" value={form.language || ''} onChange={v => set('language', v)} placeholder="Select language…" />
              : <RV>{form.language}</RV>}
          </div>
        </div>

        {/* ── Settings / Defaults ── */}
        <CollapsibleSection title="Settings" defaultOpen={false}>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4">
            <div>
              <FL>Default Commission Rate (%)</FL>
              {editable
                ? <input type="number" min={0} max={100} step={0.01} value={form.default_commission_rate ?? 0} onChange={e => set('default_commission_rate', parseFloat(e.target.value) || 0)} className={inputCls} />
                : <RV>{form.default_commission_rate ?? 0}</RV>}
            </div>

            {[
              { field: 'is_internal_customer', label: 'Is Internal Customer' },
              { field: 'so_required',          label: 'Sales Order Required' },
              { field: 'dn_required',          label: 'Delivery Note Required' },
              { field: 'is_frozen',            label: 'Is Frozen' },
              { field: 'disabled',             label: 'Disabled' },
            ].map(({ field, label }) => (
              <div key={field} className="flex items-center gap-3">
                <input
                  type="checkbox"
                  id={field}
                  checked={!!form[field as keyof Customer]}
                  onChange={e => set(field as keyof Customer, e.target.checked ? 1 : 0)}
                  disabled={!editable}
                  className="w-4 h-4 text-cyan-600 rounded"
                />
                <label htmlFor={field} className="text-sm text-gray-700 dark:text-gray-300">{label}</label>
              </div>
            ))}
          </div>
        </CollapsibleSection>

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

        {!isNew && (
          <div className="px-6 pb-6">
            <ActivityLog
              doctype="Customer"
              docname={customer?.name || customerName || ''}
              creationDate={customer?.creation}
              createdBy={customer?.owner}
              compact={false}
              initialVisible={5}
              collapsible
              startCollapsed
            />
          </div>
        )}
      </div>
    </div>
  );
};

export default CustomerDetail;
