'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { Plus, Trash2, MapPin, Phone, ToggleLeft, ToggleRight, Building2, Moon, ChevronDown, ChevronUp, Pencil } from 'lucide-react';
import { listBranches, createBranch, updateBranch, deleteBranch, type Branch } from '@client/api/branches';
import { useAuth } from '@client/contexts/AuthContext';
import { toast } from 'sonner';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import FeatureGuard from '@client/components/FeatureGuard';
import { isFeatureLockedError } from '@client/utils/isFeatureLockedError';

const HOUR_OPTIONS = Array.from({ length: 24 }, (_, h) => h);
function formatHour(h: number): string {
  const hh = String(h).padStart(2, '0');
  return `${hh}:00`;
}

interface QuietHoursEditorProps {
  branch: Branch;
  onSaved: (next: Branch) => void;
  t: (key: string, fallback?: string) => string;
}

function QuietHoursEditor({ branch, onSaved, t }: QuietHoursEditorProps) {
  const [enabled, setEnabled] = useState<boolean>(branch.quiet_hours_enabled ?? true);
  const [start, setStart] = useState<number>(branch.quiet_hours_start ?? 22);
  const [end, setEnd] = useState<number>(branch.quiet_hours_end ?? 8);
  const [saving, setSaving] = useState(false);

  const dirty =
    (branch.quiet_hours_enabled ?? true) !== enabled ||
    (branch.quiet_hours_start ?? 22) !== start ||
    (branch.quiet_hours_end ?? 8) !== end;

  async function onSave() {
    if (start === end && enabled) {
      toast.error(t('branch.quietHours.invalidWindow', 'Start and end hour cannot be identical when quiet hours are enabled.'));
      return;
    }
    setSaving(true);
    try {
      const { branch: updated } = await updateBranch(branch.id, {
        quiet_hours_enabled: enabled,
        quiet_hours_start: start,
        quiet_hours_end: end,
      });
      onSaved(updated);
      toast.success(t('branch.quietHours.saved', 'Quiet hours saved'));
    } catch (e) {
      toast.error(e instanceof Error ? e.message : t('branch.quietHours.saveFailed', 'Failed to save quiet hours'));
    } finally { setSaving(false); }
  }

  return (
    <div className="mt-3 pt-3 border-t border-dashed">
      <div className="flex items-center gap-3 flex-wrap">
        <label className="flex items-center gap-2 text-sm">
          <input type="checkbox" checked={enabled} onChange={(e) => setEnabled(e.target.checked)} />
          <span>{t('branch.quietHours.enabled', 'Quiet hours enabled')}</span>
        </label>
        <div className="flex items-center gap-2 text-sm" style={{ opacity: enabled ? 1 : 0.5 }}>
          <span>{t('branch.quietHours.from', 'From')}</span>
          <select className="input-field py-1 text-sm" value={start} onChange={(e) => setStart(parseInt(e.target.value, 10))} disabled={!enabled}>
            {HOUR_OPTIONS.map((h) => <option key={h} value={h}>{formatHour(h)}</option>)}
          </select>
          <span>{t('branch.quietHours.to', 'to')}</span>
          <select className="input-field py-1 text-sm" value={end} onChange={(e) => setEnd(parseInt(e.target.value, 10))} disabled={!enabled}>
            {HOUR_OPTIONS.map((h) => <option key={h} value={h}>{formatHour(h)}</option>)}
          </select>
          <span className="text-xs text-gray-500">{branch.timezone || 'UTC'}</span>
        </div>
        <button className="btn-primary text-xs px-3 py-1 disabled:opacity-50" onClick={onSave} disabled={!dirty || saving}>
          {saving ? '…' : t('common.save', 'Save')}
        </button>
      </div>
      <p className="text-xs text-gray-500 mt-2">
        {t('branch.quietHours.help', 'Marketing campaigns sent from this branch are paused during the quiet window. Wraps midnight (e.g. 22:00 → 08:00).')}
      </p>
    </div>
  );
}

interface WhatsAppSendRateEditorProps {
  branch: Branch;
  onSaved: (next: Branch) => void;
  t: (key: string, fallback?: string) => string;
}

function WhatsAppSendRateEditor({ branch, onSaved, t }: WhatsAppSendRateEditorProps) {
  const DEFAULT_RATE = 10;
  const [rate, setRate] = useState<number>(branch.whatsapp_send_rate ?? DEFAULT_RATE);
  const [saving, setSaving] = useState(false);

  const dirty = (branch.whatsapp_send_rate ?? DEFAULT_RATE) !== rate;

  async function onSave() {
    if (!Number.isInteger(rate) || rate < 1 || rate > 1000) {
      toast.error(t('branch.waRate.invalid', 'Send rate must be an integer between 1 and 1000.'));
      return;
    }
    setSaving(true);
    try {
      const { branch: updated } = await updateBranch(branch.id, { whatsapp_send_rate: rate });
      onSaved(updated);
      toast.success(t('branch.waRate.saved', 'WhatsApp send rate saved'));
    } catch (e) {
      toast.error(e instanceof Error ? e.message : t('branch.waRate.saveFailed', 'Failed to save send rate'));
    } finally { setSaving(false); }
  }

  return (
    <div className="mt-3 pt-3 border-t border-dashed">
      <div className="flex items-center gap-3 flex-wrap">
        <span className="text-sm font-medium">{t('branch.waRate.label', 'WhatsApp send rate')}</span>
        <div className="flex items-center gap-2 text-sm">
          <input
            type="number"
            className="input-field py-1 text-sm w-24"
            value={rate}
            min={1}
            max={1000}
            step={1}
            onChange={(e) => setRate(parseInt(e.target.value, 10) || DEFAULT_RATE)}
          />
          <span className="text-xs text-gray-500">{t('branch.waRate.unit', 'msgs / sec')}</span>
        </div>
        <button
          className="btn-primary text-xs px-3 py-1 disabled:opacity-50"
          onClick={onSave}
          disabled={!dirty || saving}
        >
          {saving ? '…' : t('common.save', 'Save')}
        </button>
      </div>
      <p className="text-xs text-gray-500 mt-2">
        {t(
          'branch.waRate.help',
          'Caps how many WhatsApp messages the campaign dispatcher sends per second from this branch. Match your Meta WABA tier: 10 = unverified / new, 80 = Standard, 1000 = High volume.',
        )}
      </p>
    </div>
  );
}

export default function BranchManagementPage() {
  const { t } = useLanguage();
  usePageHeader(t('nav.branches', 'Branch Management'), t('nav.branchesSubtitle', 'Manage restaurant locations and branches'));
  const { restaurantId } = useAuth();

  const [branchList, setBranchList] = useState<Branch[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAddModal, setShowAddModal] = useState(false);
  const [newBranch, setNewBranch] = useState({ name: '', address: '', phone: '' });
  const [saving, setSaving] = useState(false);
  const [expanded, setExpanded] = useState<Record<string, boolean>>({});

  const fetchBranches = useCallback(async () => {
    if (!restaurantId) { setLoading(false); return; }
    setLoading(true);
    try {
      const result = await listBranches();
      setBranchList(result.branches ?? []);
    } catch (err: unknown) {
      if (!isFeatureLockedError(err)) {
        toast.error(t('branch.failedToLoad', 'Failed to load branches') + ': ' + (err instanceof Error ? err.message : ''));
      }
    } finally {
      setLoading(false);
    }
  }, [restaurantId, t]);

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

  const toggleBranch = async (id: string, currentIsActive: boolean) => {
    try {
      const { branch: updated } = await updateBranch(id, { is_active: !currentIsActive });
      setBranchList(prev => prev.map(b => b.id === id ? { ...b, ...updated } : b));
      toast.success(t('branch.statusUpdated', 'Branch status updated'));
    } catch (err: unknown) {
      toast.error(t('branch.failedToUpdate', 'Failed to update branch') + ': ' + (err instanceof Error ? err.message : ''));
    }
  };

  const handleAddBranch = async () => {
    if (!restaurantId || !newBranch.name.trim()) return;
    setSaving(true);
    try {
      const { branch } = await createBranch({ name: newBranch.name, address: newBranch.address, phone: newBranch.phone, is_active: true });
      setBranchList(prev => [...prev, branch]);
      setShowAddModal(false);
      setNewBranch({ name: '', address: '', phone: '' });
      toast.success(t('branch.added', 'Branch added'));
    } catch (err: unknown) {
      toast.error(t('branch.failedToAdd', 'Failed to add branch') + ': ' + (err instanceof Error ? err.message : ''));
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteBranch(id);
      setBranchList(prev => prev.filter(b => b.id !== id));
      toast.success(t('branch.deleted', 'Branch deleted'));
    } catch (err: unknown) {
      toast.error(t('branch.failedToDelete', 'Failed to delete branch') + ': ' + (err instanceof Error ? err.message : ''));
    }
  };

  return (
    <FeatureGuard feature="multi_branch" featureName="Multi-Branch Management">
    <>
      <div className="flex items-center justify-between mb-6">
        <div>
          <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {branchList.length} {branchList.length !== 1 ? t('branch.plural', 'branches') : t('branch.singular', 'branch')}
          </p>
        </div>
        <button className="btn-primary" onClick={() => setShowAddModal(true)}>
          <Plus size={15} /> {t('branch.addBranch', 'Add Branch')}
        </button>
      </div>

      {showAddModal && (
        <div className="card p-5 mb-5">
          <h3 className="font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('branch.addNewBranch', 'Add New Branch')}</h3>
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 mb-3">
            <input className="input-base" placeholder={t('branch.namePlaceholder', 'Branch name *')} value={newBranch.name} onChange={e => setNewBranch(p => ({ ...p, name: e.target.value }))} />
            <input className="input-base" placeholder={t('common.address', 'Address')} value={newBranch.address} onChange={e => setNewBranch(p => ({ ...p, address: e.target.value }))} />
            <input className="input-base" placeholder={t('common.phone', 'Phone')} value={newBranch.phone} onChange={e => setNewBranch(p => ({ ...p, phone: e.target.value }))} />
          </div>
          <div className="flex gap-2">
            <button className="btn-primary" onClick={handleAddBranch} disabled={saving}>
              {saving ? <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : t('common.save', 'Save')}
            </button>
            <button className="btn-secondary" onClick={() => setShowAddModal(false)}>{t('common.cancel', 'Cancel')}</button>
          </div>
        </div>
      )}

      {loading ? (
        <div className="space-y-3">
          {Array.from({ length: 3 }).map((_, i) => <div key={i} className="card p-5 h-20 skeleton" />)}
        </div>
      ) : branchList.length === 0 ? (
        <div className="text-center py-16 card" style={{ color: 'hsl(var(--muted-foreground))' }}>
          <Building2 size={32} className="mx-auto mb-3 opacity-30" />
          <p className="font-medium">{t('branch.noBranches', 'No branches yet')}</p>
          <p className="text-xs mt-1">{t('branch.addFirstBranch', 'Add your first branch to get started')}</p>
        </div>
      ) : (
        <div className="space-y-3">
          {branchList.map(branch => {
            const isOpen = expanded[branch.id] === true;
            return (
              <div key={branch.id} className="card p-5">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ backgroundColor: 'hsl(var(--primary-light))' }}>
                      <Building2 size={18} style={{ color: 'hsl(var(--primary))' }} />
                    </div>
                    <div>
                      <p className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{branch.name}</p>
                      <div className="flex items-center gap-3 mt-1">
                        {branch.address && (
                          <span className="flex items-center gap-1 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                            <MapPin size={11} /> {branch.address}
                          </span>
                        )}
                        {branch.phone && (
                          <span className="flex items-center gap-1 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                            <Phone size={11} /> {branch.phone}
                          </span>
                        )}
                        <span className="flex items-center gap-1 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }} title={t('branch.quietHours.tooltip', 'Marketing quiet hours')}>
                          <Moon size={11} />
                          {(branch.quiet_hours_enabled ?? true)
                            ? `${formatHour(branch.quiet_hours_start ?? 22)}–${formatHour(branch.quiet_hours_end ?? 8)}`
                            : t('branch.quietHours.off', 'off')}
                        </span>
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    <button
                      className="btn-ghost text-xs px-2 flex items-center gap-1"
                      onClick={() => setExpanded((s) => ({ ...s, [branch.id]: !isOpen }))}
                      title={t('branch.quietHours.editTooltip', 'Edit quiet hours')}
                    >
                      <Moon size={12} />
                      {isOpen ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
                    </button>
                    <Link
                      href={`/branch-management/${branch.id}`}
                      className="btn-ghost p-1.5"
                      title={t('branch.editBranch', 'Edit branch')}
                    >
                      <Pencil size={14} />
                    </Link>
                    <button onClick={() => toggleBranch(branch.id, branch.isActive)} className="flex items-center gap-2">
                      {branch.isActive
                        ? <ToggleRight size={24} style={{ color: 'hsl(var(--success))' }} />
                        : <ToggleLeft size={24} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                      <span className="text-xs font-medium" style={{ color: branch.isActive ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))' }}>
                        {branch.isActive ? t('common.active', 'Active') : t('common.inactive', 'Inactive')}
                      </span>
                    </button>
                    <button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--danger))' }} onClick={() => handleDelete(branch.id)}>
                      <Trash2 size={14} />
                    </button>
                  </div>
                </div>
                {isOpen && (
                  <>
                    <QuietHoursEditor
                      branch={branch}
                      t={t}
                      onSaved={(updated) => setBranchList((prev) => prev.map((b) => b.id === branch.id ? { ...b, ...updated } : b))}
                    />
                    <WhatsAppSendRateEditor
                      branch={branch}
                      t={t}
                      onSaved={(updated) => setBranchList((prev) => prev.map((b) => b.id === branch.id ? { ...b, ...updated } : b))}
                    />
                  </>
                )}
              </div>
            );
          })}
        </div>
      )}
    </>
    </FeatureGuard>
  );
}
