'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Search, Plus, CheckCircle, XCircle, Clock, Eye, Ban, RefreshCw, Loader2, X } from 'lucide-react';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { toast } from 'sonner';

type TFn = (key: string, fallback?: string, vars?: Record<string, string | number>) => string;

interface Restaurant {
  id: string;
  displayId: string;
  name: string;
  owner: string;
  email: string;
  plan: string;
  status: string;
  restaurantStatus: string;
  branches: number;
  mrr: number;
  trialEnd: string | null;
  joinedDate: string;
}

const statusConfig: Record<string, { class: string; icon: React.ReactNode }> = {
  active: { class: 'badge-success', icon: <CheckCircle size={11} /> },
  trial: { class: 'badge-warning', icon: <Clock size={11} /> },
  inactive: { class: 'badge-danger', icon: <XCircle size={11} /> },
  suspended: { class: 'badge-danger', icon: <XCircle size={11} /> },
  cancelled: { class: 'badge-neutral', icon: <XCircle size={11} /> },
  past_due: { class: 'badge-danger', icon: <Clock size={11} /> },
};

const planColors: Record<string, string> = {
  Starter: 'badge-neutral',
  Growth: 'badge-primary',
  Pro: 'badge-primary',
  Enterprise: 'badge-warning',
};

function trialDaysLeft(trialEnd: string | null, t: (key: string, fallback: string) => string): string | null {
  if (!trialEnd) return null;
  const end = new Date(trialEnd);
  const now = new Date();
  const diff = Math.ceil((end.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
  if (diff < 0) return t('admin.restaurants.expired', 'Expired');
  if (diff === 0) return t('admin.restaurants.expiresToday', 'Expires today');
  return t('admin.restaurants.daysLeft', '{days}d left').replace('{days}', diff.toString());
}

const getPlans = (t: TFn) => [
    t('billing.plans.starter', 'Starter'),
    t('billing.plans.growth', 'Growth'),
    t('billing.plans.pro', 'Pro'),
    t('billing.plans.enterprise', 'Enterprise'),
  ];

function OnboardModal({ onClose, onSuccess, t }: { onClose: () => void; onSuccess: () => void; t: TFn }) {
  const [form, setForm] = useState({
    restaurantName: '',
    ownerName: '',
    ownerEmail: '',
    ownerPassword: '',
    plan: 'Starter',
  });
  const [saving, setSaving] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const validate = () => {
    const e: Record<string, string> = {};
    if (!form.restaurantName.trim()) e.restaurantName = t('admin.restaurants.restaurantNameRequired', 'Restaurant name is required');
    if (!form.ownerEmail.trim()) e.ownerEmail = t('admin.restaurants.ownerEmailRequired', 'Owner email is required');
    if (form.ownerEmail && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.ownerEmail)) e.ownerEmail = t('admin.restaurants.invalidEmail', 'Invalid email address');
    if (form.ownerPassword && form.ownerPassword.length < 8) e.ownerPassword = t('admin.restaurants.passwordLength', 'Password must be at least 8 characters');
    return e;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length > 0) { setErrors(errs); return; }
    setSaving(true);
    try {
      const res = await fetch('/api/admin/restaurants', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error?.message ?? t('admin.restaurants.failedToCreate', 'Failed to create restaurant'));
      const tempPwd = data.restaurant?.tempPassword;
      if (tempPwd) {
        toast.success(
          t('admin.restaurants.createdWithPass', 'Restaurant "{name}" created ({id}). Temp password: {pwd}')
            .replace('{name}', form.restaurantName)
            .replace('{id}', data.restaurant?.displayId ?? '')
            .replace('{pwd}', tempPwd),
          { duration: 10000 }
        );
      } else {
        toast.success(
          t('admin.restaurants.created', 'Restaurant "{name}" created ({id})')
            .replace('{name}', form.restaurantName)
            .replace('{id}', data.restaurant?.displayId ?? '')
        );
      }
      onSuccess();
      onClose();
    } catch (err: unknown) {
      toast.error(err instanceof Error ? err.message : t('admin.restaurants.failedToCreate', 'Failed to create restaurant'));
    } finally {
      setSaving(false);
    }
  };

  const field = (key: keyof typeof form) => ({
    value: form[key],
    onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
      setForm(prev => ({ ...prev, [key]: e.target.value }));
      if (errors[key]) setErrors(prev => ({ ...prev, [key]: '' }));
    },
  });

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4" style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}>
      <div className="card w-full max-w-md p-6 relative" style={{ maxHeight: '90vh', overflowY: 'auto' }}>
        <button onClick={onClose} className="absolute top-4 right-4 btn-ghost p-1.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
          <X size={16} />
        </button>
        <h2 className="font-bold text-lg mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.restaurants.onboardRestaurant', 'Onboard Restaurant')}</h2>
        <p className="text-sm mb-5" style={{ color: 'hsl(var(--muted-foreground))' }}>
          {t('admin.restaurants.onboardDescription', 'Create a new restaurant account with a 14-day trial.')}
        </p>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
              {t('admin.restaurants.restaurantName', 'Restaurant Name')} <span style={{ color: 'hsl(var(--danger))' }}>*</span>
            </label>
            <input className="input-base w-full" placeholder={t('admin.restaurants.restaurantNamePlaceholder', 'e.g. The Rustic Fork')} {...field('restaurantName')} />
            {errors.restaurantName && <p className="text-xs mt-1" style={{ color: 'hsl(var(--danger))' }}>{errors.restaurantName}</p>}
          </div>
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.restaurants.ownerName', 'Owner Name')}</label>
            <input className="input-base w-full" placeholder={t('admin.restaurants.ownerNamePlaceholder', 'e.g. Jane Smith')} {...field('ownerName')} />
          </div>
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
              {t('admin.restaurants.ownerEmail', 'Owner Email')} <span style={{ color: 'hsl(var(--danger))' }}>*</span>
            </label>
            <input type="email" className="input-base w-full" placeholder={t('admin.restaurants.ownerEmailPlaceholder', 'owner@restaurant.com')} {...field('ownerEmail')} />
            {errors.ownerEmail && <p className="text-xs mt-1" style={{ color: 'hsl(var(--danger))' }}>{errors.ownerEmail}</p>}
          </div>
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
              {t('admin.restaurants.ownerPassword', 'Owner Password')} <span className="font-normal" style={{ color: 'hsl(var(--muted-foreground))' }}>({t('admin.restaurants.optionalAutoGenerated', 'optional — auto-generated if blank')})</span>
            </label>
            <input type="password" className="input-base w-full" placeholder={t('admin.restaurants.passwordPlaceholder', 'Leave blank to auto-generate')} {...field('ownerPassword')} />
            {errors.ownerPassword && <p className="text-xs mt-1" style={{ color: 'hsl(var(--danger))' }}>{errors.ownerPassword}</p>}
          </div>
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.restaurants.plan', 'Plan')}</label>
            <select className="input-base w-full" {...field('plan')}>
              {getPlans(t).map(p => <option key={p} value={p}>{p}</option>)}
            </select>
          </div>
          <div className="flex gap-3 pt-2">
            <button type="button" onClick={onClose} className="btn-secondary flex-1">{t('admin.restaurants.cancel', 'Cancel')}</button>
            <button type="submit" disabled={saving} className="btn-primary flex-1 flex items-center justify-center gap-2">
              {saving ? <Loader2 size={14} className="animate-spin" /> : <Plus size={14} />}
              {saving ? t('admin.restaurants.creating', 'Creating…') : t('admin.restaurants.createRestaurant', 'Create Restaurant')}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

export default function RestaurantManagementPage() {
  const { t, currentLang } = useLanguage();
  usePageHeader(t('admin.restaurants.pageTitle', 'Restaurant Management'), t('admin.restaurants.pageDescription', 'Onboard, suspend, and manage all tenants'));
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [restaurants, setRestaurants] = useState<Restaurant[]>([]);
  const [loading, setLoading] = useState(true);
  const [showOnboard, setShowOnboard] = useState(false);

  const loadRestaurants = () => {
    setLoading(true);
    fetch('/api/admin/restaurants')
      .then(r => r.json())
      .then(data => setRestaurants(data.restaurants ?? []))
      .catch(() => toast.error(t('admin.restaurants.failedToLoad', 'Failed to load restaurants')))
      .finally(() => setLoading(false));
  };

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

  const filtered = restaurants.filter(r => {
    const matchSearch =
      r.name.toLowerCase().includes(search.toLowerCase()) ||
      r.owner.toLowerCase().includes(search.toLowerCase()) ||
      r.email.toLowerCase().includes(search.toLowerCase()) ||
      (r.displayId ?? '').toLowerCase().includes(search.toLowerCase());
    const matchStatus = statusFilter === 'all' || r.status === statusFilter;
    return matchSearch && matchStatus;
  });

  const statusCounts = ['active', 'trial', 'inactive', 'suspended', 'cancelled'].reduce<Record<string, number>>(
    (acc, s) => ({ ...acc, [s]: restaurants.filter(r => r.status === s).length }),
    {}
  );

  return (
    <>
      {showOnboard && (
        <OnboardModal onClose={() => setShowOnboard(false)} onSuccess={loadRestaurants} t={t} />
      )}

      <div className="flex items-center gap-3 px-4 py-3 rounded-xl mb-6" style={{ backgroundColor: 'hsl(231, 40%, 14%)', color: 'white' }}>
        <div className="w-2 h-2 rounded-full bg-orange-400 animate-pulse" />
        <span className="text-sm font-semibold">{t('admin.restaurants.adminPanel', 'Admin Panel')}</span>
        <span className="text-xs opacity-60">
          {loading ? `— ${t('admin.restaurants.loadingDots', 'Loading…')}` : `— ${t('admin.restaurants.managingCount', 'Managing {count} restaurant account{plural}').replace('{count}', restaurants.length.toString()).replace('{plural}', restaurants.length !== 1 ? 's' : '')}`}
        </span>
      </div>

      <div className="flex flex-col sm:flex-row gap-3 mb-5">
        <div className="relative flex-1 max-w-sm">
          <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
          <input className="input-base pl-9" placeholder={t('admin.restaurants.searchPlaceholder', 'Search by name, owner, email, ID…')} value={search} onChange={e => setSearch(e.target.value)} />
        </div>
        <div className="flex gap-2 flex-wrap">
          {(['all', 'active', 'trial', 'inactive', 'cancelled'] as const).map(s => (
            <button
              key={s}
              onClick={() => setStatusFilter(s)}
              className={`px-3 py-1.5 rounded-lg text-sm font-medium capitalize transition-all ${statusFilter === s ? 'btn-primary' : 'btn-secondary'}`}
            >
              {t(`admin.restaurants.status.${s}`, s)}
              {s !== 'all' && statusCounts[s] != null && statusCounts[s] > 0 && (
                <span className="ml-1.5 text-xs opacity-70">({statusCounts[s]})</span>
              )}
            </button>
          ))}
        </div>
        <button
          onClick={() => setShowOnboard(true)}
          className="btn-primary ml-auto flex items-center gap-1.5"
        >
          <Plus size={15} /> {t('admin.restaurants.onboard', 'Onboard')}
        </button>
      </div>

      <div className="card overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center py-16 gap-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
            <Loader2 size={18} className="animate-spin" /> {t('admin.restaurants.loadingRestaurants', 'Loading restaurants…')}
          </div>
        ) : filtered.length === 0 ? (
          <div className="text-center py-16" style={{ color: 'hsl(var(--muted-foreground))' }}>
            <p className="text-sm">{t('admin.restaurants.noRestaurantsFound', 'No restaurants found.')}</p>
          </div>
        ) : (
          <table className="w-full">
            <thead>
              <tr style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                {[
                  { key: 'restaurant', label: 'Restaurant' },
                  { key: 'id', label: 'ID' },
                  { key: 'plan', label: 'Plan' },
                  { key: 'status', label: 'Status' },
                  { key: 'branches', label: 'Branches' },
                  { key: 'mrr', label: 'MRR' },
                  { key: 'joined', label: 'Joined' },
                  { key: 'actions', label: 'Actions' }
                ].map(h => (
                  <th key={h.key} className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {t(`admin.restaurants.table.${h.key}`, h.label)}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map((r, idx) => {
                const sc = statusConfig[r.status] ?? statusConfig['inactive'];
                const planBadge = planColors[r.plan] ?? 'badge-neutral';
                const daysLeft = r.status === 'trial' ? trialDaysLeft(r.trialEnd, t) : null;
                return (
                  <tr key={r.id} className="table-row-hover" style={{ borderBottom: idx < filtered.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded-lg flex items-center justify-center text-white text-xs font-bold shrink-0" style={{ backgroundColor: 'hsl(231, 40%, 14%)' }}>
                          {r.name[0]?.toUpperCase() ?? '?'}
                        </div>
                        <div>
                          <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{r.name}</p>
                          <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{r.email || r.owner}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <span className="text-xs font-mono font-semibold px-2 py-1 rounded-lg" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground-secondary))' }}>
                        {r.displayId}
                      </span>
                    </td>
                    <td className="px-4 py-3"><span className={`badge ${planBadge}`}>{r.plan}</span></td>
                    <td className="px-4 py-3">
                      <div className="flex flex-col gap-0.5">
                        <span className={`badge ${sc.class} flex items-center gap-1 w-fit`}>{sc.icon} {t(`admin.restaurants.status.${r.status}`, r.status)}</span>
                        {daysLeft && (
                          <span className="text-xs" style={{ color: daysLeft === t('admin.restaurants.expired', 'Expired') ? 'hsl(var(--danger))' : 'hsl(var(--muted-foreground))' }}>
                            {daysLeft}
                          </span>
                        )}
                      </div>
                    </td>
                    <td className="px-4 py-3 text-sm tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>{r.branches}</td>
                    <td className="px-4 py-3 font-semibold tabular-nums text-sm" style={{ color: r.mrr > 0 ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))' }}>
                      {r.mrr > 0 ? `$${r.mrr.toFixed(0)}` : '—'}
                    </td>
                    <td className="px-4 py-3 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {new Date(r.joinedDate).toLocaleDateString(currentLang, { month: 'short', day: 'numeric', year: 'numeric' })}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-1">
                        <Link href={`/admin/restaurants/${r.id}`} className="btn-ghost p-1.5" title={t('admin.restaurants.view', 'View')}>
                          <Eye size={14} />
                        </Link>
                        {r.restaurantStatus === 'active' && (
                          <button className="btn-ghost p-1.5" title={t('admin.restaurants.suspend', 'Suspend')} style={{ color: 'hsl(var(--danger))' }}>
                            <Ban size={14} />
                          </button>
                        )}
                        {r.restaurantStatus === 'suspended' && (
                          <button className="btn-ghost p-1.5" title={t('admin.restaurants.reactivate', 'Reactivate')} style={{ color: 'hsl(var(--success))' }}>
                            <RefreshCw size={14} />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </>
  );
}
