'use client';

import { useState } from 'react';
import Link from 'next/link';
import { ArrowLeft, Save, User, Mail, Shield, Building2, ToggleLeft, ToggleRight, AlertCircle } from 'lucide-react';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

const roles = ['Manager', 'Supervisor', 'Waiter', 'Kitchen Staff', 'Host', 'Cashier'];
const branches = ['The Rustic Fork — Downtown', 'The Rustic Fork — Marina', 'The Rustic Fork — Mission'];
const allPermissions = [
  { key: 'orders', label: 'Order Management', desc: 'View and manage orders' },
  { key: 'bookings', label: 'Reservations', desc: 'View and manage bookings' },
  { key: 'menu', label: 'Menu Management', desc: 'Edit menu items and categories' },
  { key: 'staff', label: 'Staff Management', desc: 'Manage team members' },
  { key: 'analytics', label: 'Analytics', desc: 'View reports and analytics' },
  { key: 'settings', label: 'Settings', desc: 'Modify restaurant settings' },
  { key: 'customers', label: 'Customer Data', desc: 'Access customer profiles' },
  { key: 'ai_config', label: 'AI Configuration', desc: 'Configure AI agent settings' },
];

interface FormErrors {
  name?: string;
  email?: string;
  role?: string;
  branch?: string;
}

function FieldError({ message }: { message?: string }) {
  if (!message) return null;
  return (
    <p className="flex items-center gap-1 text-xs mt-1.5 font-medium" style={{ color: 'hsl(0, 84%, 44%)' }}>
      <AlertCircle size={12} />
      {message}
    </p>
  );
}

export default function StaffFormPage({ params }: { params: { id?: string } }) {
  const { t } = useLanguage();
  const isEdit = params?.id && params.id !== 'new';
  usePageHeader(isEdit ? t('staff.editStaffMember', "Edit Staff Member") : t('staff.addStaffMember', "Add Staff Member"), t('staff.manageTeamMemberDetailsAndPermissions', "Manage team member details and permissions"));
  const [form, setForm] = useState({
    name: isEdit ? 'Marco Rossi' : '',
    email: isEdit ? 'marco@rusticfork.com' : '',
    role: isEdit ? 'Manager' : '',
    branch: isEdit ? 'The Rustic Fork — Downtown' : '',
    active: true,
    permissions: isEdit ? ['orders', 'bookings', 'menu', 'staff', 'analytics'] : [] as string[],
  });
  const [errors, setErrors] = useState<FormErrors>({});
  const [touched, setTouched] = useState<Record<string, boolean>>({});
  const [saving, setSaving] = useState(false);

  const validators: Record<string, (val: string) => string | undefined> = {
    name: (v) => !v.trim() ? t('staff.fullNameIsRequired', 'Full name is required') : v.trim().length < 2 ? t('staff.nameMustBeAtLeast2Characters', 'Name must be at least 2 characters') : undefined,
    email: (v) => !v.trim() ? t('staff.emailAddressIsRequired', 'Email address is required') : !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) ? t('staff.pleaseEnterAValidEmailAddress', 'Please enter a valid email address') : undefined,
    role: (v) => !v ? t('staff.pleaseSelectARole', 'Please select a role') : undefined,
    branch: (v) => !v ? t('staff.pleaseAssignABranch', 'Please assign a branch') : undefined,
  };

  const handleBlur = (field: string) => {
    setTouched(prev => ({ ...prev, [field]: true }));
    setErrors(prev => ({ ...prev, [field]: validators[field]?.(form[field as keyof typeof form] as string) }));
  };

  const handleChange = (field: string, value: string) => {
    setForm(f => ({ ...f, [field]: value }));
    if (touched[field]) setErrors(prev => ({ ...prev, [field]: validators[field]?.(value) }));
  };

  const validate = (): boolean => {
    const newErrors: FormErrors = {};
    const newTouched: Record<string, boolean> = {};
    ['name', 'email', 'role', 'branch'].forEach(field => {
      newTouched[field] = true;
      const err = validators[field]?.(form[field as keyof typeof form] as string);
      if (err) newErrors[field as keyof FormErrors] = err;
    });
    setErrors(newErrors);
    setTouched(prev => ({ ...prev, ...newTouched }));
    return Object.keys(newErrors).length === 0;
  };

  const handleSave = () => {
    if (!validate()) return;
    setSaving(true);
    setTimeout(() => {
      setSaving(false);
    }, 1200);
  };

  const togglePermission = (key: string) => {
    setForm(f => ({
      ...f,
      permissions: f.permissions.includes(key) ? f.permissions.filter(p => p !== key) : [...f.permissions, key],
    }));
  };

  const selectAllForRole = (role: string) => {
    const rolePerms: Record<string, string[]> = {
      Manager: ['orders', 'bookings', 'menu', 'staff', 'analytics', 'settings', 'customers', 'ai_config'],
      Supervisor: ['orders', 'bookings', 'menu', 'analytics', 'customers'],
      Waiter: ['orders', 'bookings'],
      'Kitchen Staff': ['orders'],
      Host: ['bookings'],
      Cashier: ['orders'],
    };
    handleChange('role', role);
    setForm(f => ({ ...f, role, permissions: rolePerms[role] || [] }));
    if (touched.role) setErrors(prev => ({ ...prev, role: validators.role?.(role) }));
  };

  const inputStyle = (field: string) => ({
    borderColor: touched[field] && errors[field as keyof FormErrors] ? 'hsl(0, 84%, 44%)' : undefined,
    boxShadow: touched[field] && errors[field as keyof FormErrors] ? '0 0 0 2px hsl(0, 84%, 44%, 0.15)' : undefined,
  });

  return (
    <>
      <div className="flex items-center gap-3 mb-6">
        <Link href="/staff" className="btn-ghost p-1.5"><ArrowLeft size={16} /></Link>
        <h2 className="font-bold text-lg" style={{ color: 'hsl(var(--foreground))' }}>{isEdit ? t('staff.editStaffMember', 'Edit Staff Member') : t('staff.addNewStaffMember', 'Add New Staff Member')}</h2>
        <div className="ml-auto flex gap-2">
          <Link href="/staff" className="btn-secondary">{t('common.cancel', 'Cancel')}</Link>
          <button className="btn-primary inline-flex items-center gap-2" onClick={handleSave} disabled={saving}>
            {saving ? (
              <>
                <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                {t('common.saving', 'Saving...')}
              </>
            ) : (
              <><Save size={15} /> {isEdit ? t('common.saveChanges', 'Save Changes') : t('staff.addStaff', 'Add Staff')}</>
            )}
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        <div className="lg:col-span-2 space-y-5">
          {/* Basic info */}
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('staff.personalInformation', 'Personal Information')}</h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('staff.fullName', 'Full Name')} *</label>
                <div className="relative">
                  <User size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: touched.name && errors.name ? 'hsl(0, 84%, 44%)' : 'hsl(var(--muted-foreground))' }} />
                  <input
                    className="input-base pl-9"
                    placeholder={t('staff.placeholderName', 'John Smith')}
                    value={form.name}
                    onChange={e => handleChange('name', e.target.value)}
                    onBlur={() => handleBlur('name')}
                    style={inputStyle('name')}
                  />
                </div>
                <FieldError message={touched.name ? errors.name : undefined} />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('staff.emailAddress', 'Email Address')} *</label>
                <div className="relative">
                  <Mail size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: touched.email && errors.email ? 'hsl(0, 84%, 44%)' : 'hsl(var(--muted-foreground))' }} />
                  <input
                    type="email"
                    className="input-base pl-9"
                    placeholder={t('staff.placeholderEmail', 'john@restaurant.com')}
                    value={form.email}
                    onChange={e => handleChange('email', e.target.value)}
                    onBlur={() => handleBlur('email')}
                    style={inputStyle('email')}
                  />
                </div>
                <FieldError message={touched.email ? errors.email : undefined} />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('staff.role', 'Role')} *</label>
                <div className="relative">
                  <Shield size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: touched.role && errors.role ? 'hsl(0, 84%, 44%)' : 'hsl(var(--muted-foreground))' }} />
                  <select
                    className="input-base pl-9"
                    value={form.role}
                    onChange={e => selectAllForRole(e.target.value)}
                    onBlur={() => handleBlur('role')}
                    style={inputStyle('role')}
                  >
                    <option value="">{t('staff.selectRole', 'Select role')}</option>
                    {roles.map(r => <option key={r} value={r}>{t(`staff.roles.${r.toLowerCase().replace(' ', '_')}`, r)}</option>)}
                  </select>
                </div>
                <FieldError message={touched.role ? errors.role : undefined} />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('staff.branchAssignment', 'Branch Assignment')} *</label>
                <div className="relative">
                  <Building2 size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: touched.branch && errors.branch ? 'hsl(0, 84%, 44%)' : 'hsl(var(--muted-foreground))' }} />
                  <select
                    className="input-base pl-9"
                    value={form.branch}
                    onChange={e => handleChange('branch', e.target.value)}
                    onBlur={() => handleBlur('branch')}
                    style={inputStyle('branch')}
                  >
                    <option value="">{t('staff.selectBranch', 'Select branch')}</option>
                    {branches.map(b => <option key={b} value={b}>{b}</option>)}
                  </select>
                </div>
                <FieldError message={touched.branch ? errors.branch : undefined} />
              </div>
            </div>
          </div>

          {/* Permissions */}
          <div className="card p-5">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('staff.permissions', 'Permissions')}</h3>
              <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{form.permissions.length} {t('common.of', 'of')} {allPermissions.length} {t('staff.enabled', 'enabled')}</span>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              {allPermissions.map(perm => {
                const has = form.permissions.includes(perm.key);
                return (
                  <div
                    key={perm.key}
                    className="flex items-center justify-between p-3 rounded-xl border cursor-pointer transition-all"
                    style={{
                      borderColor: has ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                      backgroundColor: has ? 'hsl(var(--primary-light))' : 'hsl(var(--surface))',
                    }}
                    onClick={() => togglePermission(perm.key)}
                  >
                    <div>
                      <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t(`staff.permissionLabels.${perm.key}`, perm.label)}</p>
                      <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t(`staff.permissionDescs.${perm.key}`, perm.desc)}</p>
                    </div>
                    <div className="w-5 h-5 rounded border-2 flex items-center justify-center shrink-0 transition-all"
                      style={{ borderColor: has ? 'hsl(var(--primary))' : 'hsl(var(--border))', backgroundColor: has ? 'hsl(var(--primary))' : 'transparent' }}>
                      {has && <svg width="10" height="8" viewBox="0 0 10 8" fill="none"><path d="M1 4L3.5 6.5L9 1" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /></svg>}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* Right: Status */}
        <div className="space-y-5">
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('staff.accountStatus', 'Account Status')}</h3>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('staff.activeAccount', 'Active Account')}</p>
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('staff.activeAccountDesc', 'Staff can log in and access the system')}</p>
              </div>
              <button onClick={() => setForm(f => ({ ...f, active: !f.active }))}>
                {form.active ? <ToggleRight size={28} style={{ color: 'hsl(var(--success))' }} /> : <ToggleLeft size={28} style={{ color: 'hsl(var(--muted-foreground))' }} />}
              </button>
            </div>
          </div>

          {form.role && (
            <div className="card p-5">
              <h3 className="font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('staff.roleSummary', 'Role Summary')}</h3>
              <div className="p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--primary-light))' }}>
                <p className="font-semibold text-sm" style={{ color: 'hsl(var(--primary))' }}>{t(`staff.roles.${form.role.toLowerCase().replace(' ', '_')}`, form.role)}</p>
                <p className="text-xs mt-1" style={{ color: 'hsl(var(--primary))' }}>{form.permissions.length} {t('staff.permissionsEnabled', 'permissions enabled')}</p>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
}
