'use client';

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

const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
const timezones = [
  { value: 'America/Los_Angeles', label: 'Pacific Time (PT)' },
  { value: 'America/Denver', label: 'Mountain Time (MT)' },
  { value: 'America/Chicago', label: 'Central Time (CT)' },
  { value: 'America/New_York', label: 'Eastern Time (ET)' },
];

interface DayHours {
  open: boolean;
  from: string;
  to: string;
}

interface FormErrors {
  name?: string;
  address?: string;
  phone?: 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 BranchFormPage({ params }: { params: { id?: string } }) {
  const { t } = useLanguage();
  const isEdit = params?.id && params.id !== 'new';
  usePageHeader(isEdit ? t('branchManagement.editBranch', "Edit Branch") : t('branchManagement.addBranch', "Add Branch"), t('branchManagement.manageSubtitle', "Manage branch details and operating hours"));
  const [form, setForm] = useState({
    name: isEdit ? 'The Rustic Fork — Downtown' : '',
    address: isEdit ? '142 Oak Street, San Francisco, CA 94102' : '',
    phone: isEdit ? '+1 (555) 234-5678' : '',
    timezone: 'America/Los_Angeles',
    active: true,
  });
  const [hours, setHours] = useState<Record<string, DayHours>>(
    Object.fromEntries(days.map(d => [d, { open: !['Sunday'].includes(d), from: '09:00', to: '22:00' }]))
  );
  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('branchManagement.errorNameRequired', 'Branch name is required') : v.trim().length < 2 ? t('branchManagement.errorNameTooShort', 'Name must be at least 2 characters') : undefined,
    address: (v) => !v.trim() ? t('branchManagement.errorAddressRequired', 'Address is required') : v.trim().length < 10 ? t('branchManagement.errorAddressTooShort', 'Please enter a complete address') : undefined,
    phone: (v) => v && !/^[\+\d\s\(\)\-]{7,20}$/.test(v) ? t('branchManagement.errorPhoneInvalid', 'Please enter a valid phone number') : 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', 'address', 'phone'].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 toggleDay = (day: string) => {
    setHours(h => ({ ...h, [day]: { ...h[day], open: !h[day].open } }));
  };

  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="/branch-management" className="btn-ghost p-1.5"><ArrowLeft size={16} /></Link>
        <h2 className="font-bold text-lg" style={{ color: 'hsl(var(--foreground))' }}>{isEdit ? t('branchManagement.editBranch', 'Edit Branch') : t('branchManagement.addNewBranch', 'Add New Branch')}</h2>
        <div className="ml-auto flex gap-2">
          <Link href="/branch-management" className="btn-secondary">{t('branchManagement.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('branchManagement.saving', 'Saving...')}
              </>
            ) : (
              <><Save size={15} /> {isEdit ? t('branchManagement.saveChanges', 'Save Changes') : t('branchManagement.addBranch', 'Add Branch')}</>
            )}
          </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('branchManagement.branchInformation', 'Branch Information')}</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('branchManagement.labelBranchName', 'Branch Name *')}</label>
                <div className="relative">
                  <Building2 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('branchManagement.placeholderBranchName', "e.g. The Rustic Fork — Sunset")}
                    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('branchManagement.labelFullAddress', 'Full Address *')}</label>
                <div className="relative">
                  <MapPin size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: touched.address && errors.address ? 'hsl(0, 84%, 44%)' : 'hsl(var(--muted-foreground))' }} />
                  <input
                    className="input-base pl-9"
                    placeholder={t('branchManagement.placeholderAddress', "123 Main Street, City, State, ZIP")}
                    value={form.address}
                    onChange={e => handleChange('address', e.target.value)}
                    onBlur={() => handleBlur('address')}
                    style={inputStyle('address')}
                  />
                </div>
                <FieldError message={touched.address ? errors.address : undefined} />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('branchManagement.labelPhone', 'Phone Number')}</label>
                  <div className="relative">
                    <Phone size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: touched.phone && errors.phone ? 'hsl(0, 84%, 44%)' : 'hsl(var(--muted-foreground))' }} />
                    <input
                      className="input-base pl-9"
                      placeholder="+1 (555) 000-0000"
                      value={form.phone}
                      onChange={e => handleChange('phone', e.target.value)}
                      onBlur={() => handleBlur('phone')}
                      style={inputStyle('phone')}
                    />
                  </div>
                  <FieldError message={touched.phone ? errors.phone : undefined} />
                </div>
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('branchManagement.labelTimezone', 'Timezone')}</label>
                  <div className="relative">
                    <Globe size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                    <select className="input-base pl-9" value={form.timezone} onChange={e => setForm(f => ({ ...f, timezone: e.target.value }))}>
                      {timezones.map(tz => <option key={tz.value} value={tz.value}>{t(`branchManagement.timezone.${tz.value}`, tz.label)}</option>)}
                    </select>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Operating hours */}
          <div className="card p-5">
            <div className="flex items-center gap-2 mb-4">
              <Clock size={16} style={{ color: 'hsl(var(--primary))' }} />
              <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('branchManagement.operatingHours', 'Operating Hours')}</h3>
            </div>
            <div className="space-y-2">
              {days.map(day => (
                <div key={day} className="flex items-center gap-4 py-2" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                  <div className="w-28 flex items-center gap-2">
                    <button onClick={() => toggleDay(day)}>
                      {hours[day].open ? <ToggleRight size={20} style={{ color: 'hsl(var(--success))' }} /> : <ToggleLeft size={20} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                    </button>
                    <span className="text-sm font-medium" style={{ color: hours[day].open ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}>{t(`common.days.${day.toLowerCase()}.short`, day.slice(0, 3))}</span>
                  </div>
                  {hours[day].open ? (
                    <div className="flex items-center gap-2 flex-1">
                      <input type="time" className="input-base py-1 text-sm" value={hours[day].from} onChange={e => setHours(h => ({ ...h, [day]: { ...h[day], from: e.target.value } }))} />
                      <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('common.to', 'to')}</span>
                      <input type="time" className="input-base py-1 text-sm" value={hours[day].to} onChange={e => setHours(h => ({ ...h, [day]: { ...h[day], to: e.target.value } }))} />
                    </div>
                  ) : (
                    <span className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('common.closed', 'Closed')}</span>
                  )}
                </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('branchManagement.branchStatus', 'Branch Status')}</h3>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('branchManagement.activeBranch', 'Active Branch')}</p>
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('branchManagement.activeBranchDesc', 'Branch is visible and accepting orders')}</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>
          <div className="card p-5">
            <h3 className="font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('branchManagement.quickSummary', 'Quick Summary')}</h3>
            <div className="space-y-2 text-xs">
              {[
                { label: t('branchManagement.summaryOpenDays', 'Open Days'), value: t('branchManagement.summaryDaysValue', `${Object.values(hours).filter(h => h.open).length} days/week`).replace('{{count}}', String(Object.values(hours).filter(h => h.open).length)) },
                { label: t('branchManagement.labelTimezone', 'Timezone'), value: t(`branchManagement.timezone.${form.timezone}`, timezones.find(t => t.value === form.timezone)?.label || '') },
              ].map(item => (
                <div key={item.label} className="flex justify-between">
                  <span style={{ color: 'hsl(var(--muted-foreground))' }}>{item.label}</span>
                  <span className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>{item.value}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
