'use client';

import { useState, useEffect, useCallback } from 'react';
import { Plus, Trash2, MapPin, Phone, ToggleLeft, ToggleRight, Building2 } 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';

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 fetchBranches = useCallback(async () => {
    if (!restaurantId) { setLoading(false); return; }
    setLoading(true);
    try {
      const result = await listBranches();
      setBranchList(result.branches ?? []);
    } catch (err: unknown) {
      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">
    <>
      <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 => (
            <div key={branch.id} className="card p-5 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>
                    )}
                  </div>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <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>
          ))}
        </div>
      )}
    </>
    </FeatureGuard>
  );
}
