'use client';

import { use, useState, useEffect, useMemo } 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';
import { getAllTimezones } from '@client/data/timezones';
import { getBranch, updateBranch, createBranch } from '@client/api/branches';

const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

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: Promise<{ id?: string }> }) {
  const { id } = use(params);
  const { t } = useLanguage();
  const isEdit = id && 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: '',
    address: '',
    phone: '',
    timezone: 'UTC',
    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 [loading, setLoading] = useState(!!isEdit);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [timezoneSearch, setTimezoneSearch] = useState('');
  const [saveError, setSaveError] = useState<string | null>(null);

  const allTimezones = useMemo(() => getAllTimezones(), []);
  const filteredTimezones = useMemo(() => {
    const q = timezoneSearch.toLowerCase();
    if (!q) return allTimezones;
    return allTimezones.filter(tz => tz.zone.toLowerCase().includes(q) || tz.label.toLowerCase().includes(q));
  }, [allTimezones, timezoneSearch]);

  useEffect(() => {
    if (!isEdit) return;
    let cancelled = false;
    setLoading(true);
    getBranch(id as string)
      .then(({ branch }) => {
        if (cancelled) return;
        setForm({
          name: branch.name || '',
          address: branch.address || '',
          phone: branch.phone || '',
          timezone: branch.timezone || 'UTC',
          active: branch.isActive,
        });
        if (branch.hours) {
          const rawHours = branch.hours as Record<string, unknown> | null;
          if (rawHours && typeof rawHours === 'object') {
            const mapped: Record<string, DayHours> = {};
            for (const day of days) {
              const raw = rawHours[day] as { open?: boolean; from?: string; to?: string } | undefined;
              mapped[day] = raw
                ? { open: !!raw.open, from: raw.from || '09:00', to: raw.to || '22:00' }
                : { open: !['Sunday'].includes(day), from: '09:00', to: '22:00' };
            }
            setHours(mapped);
          }
        }
      })
      .catch((err) => {
        if (!cancelled) setLoadError(err instanceof Error ? err.message : 'Failed to load branch data');
      })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [isEdit, id]);

  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 < 5 ? 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 = async () => {
    if (!validate()) return;
    setSaving(true);
    setSaveError(null);
    try {
      const payload = {
        name: form.name.trim(),
        address: form.address.trim() || null,
        phone: form.phone.trim() || null,
        timezone: form.timezone,
        is_active: form.active,
        hours,
      };
      if (isEdit) {
        await updateBranch(id as string, payload);
      } else {
        await createBranch(payload);
      }
      window.location.href = '/branch-management';
    } catch (err) {
      setSaveError(err instanceof Error ? err.message : 'Failed to save branch');
    } finally {
      setSaving(false);
    }
  };

  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,
  });

  const currentTzLabel = allTimezones.find(tz => tz.zone === form.timezone)?.label || form.timezone;

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <span className="w-6 h-6 border-2 border-primary/30 border-t-primary rounded-full animate-spin" />
      </div>
    );
  }

  if (loadError) {
    return (
      <div className="flex flex-col items-center gap-4 py-20">
        <div className="rounded-lg px-5 py-4 text-sm flex items-center gap-2 max-w-md w-full" style={{ backgroundColor: 'hsl(0, 84%, 44%, 0.1)', color: 'hsl(0, 84%, 44%)', border: '1px solid hsl(0, 84%, 44%, 0.3)' }}>
          <AlertCircle size={15} className="shrink-0" />
          {loadError}
        </div>
        <Link href="/branch-management" className="btn-secondary">{t('branchManagement.cancel', 'Back')}</Link>
      </div>
    );
  }

  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>

      {saveError && (
        <div className="mb-4 rounded-lg px-4 py-3 text-sm flex items-center gap-2" style={{ backgroundColor: 'hsl(0, 84%, 44%, 0.1)', color: 'hsl(0, 84%, 44%)', border: '1px solid hsl(0, 84%, 44%, 0.3)' }}>
          <AlertCircle size={14} />
          {saveError}
        </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. Downtown Branch")}
                    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>
                <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>
          </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>

            {/* Timezone selector — at top of hours card */}
            <div className="mb-5 pb-4" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
              <label className="block text-xs font-semibold mb-0.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                <Globe size={11} className="inline mr-1" />
                {t('branch.timezone.label', 'Timezone')}
              </label>
              <p className="text-xs mb-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
                {t('branch.timezone.hint', 'All operating hours are interpreted in this timezone.')}
              </p>
              <input
                className="input-base mb-1.5 text-sm"
                placeholder={t('branch.timezone.search', 'Search timezone…')}
                value={timezoneSearch}
                onChange={e => setTimezoneSearch(e.target.value)}
              />
              <select
                className="input-base text-sm"
                value={form.timezone}
                onChange={e => { setForm(f => ({ ...f, timezone: e.target.value })); setTimezoneSearch(''); }}
                size={filteredTimezones.length > 0 && timezoneSearch ? Math.min(6, filteredTimezones.length) : 1}
              >
                {filteredTimezones.map(tz => (
                  <option key={tz.zone} value={tz.zone}>{tz.label}</option>
                ))}
                {filteredTimezones.length === 0 && (
                  <option disabled value="">{t('branch.timezone.noMatches', 'No matches')}</option>
                )}
              </select>
            </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('branch.timezone.label', 'Timezone'), value: currentTzLabel },
              ].map(item => (
                <div key={item.label} className="flex justify-between gap-2">
                  <span style={{ color: 'hsl(var(--muted-foreground))' }}>{item.label}</span>
                  <span className="font-medium text-right truncate max-w-[140px]" style={{ color: 'hsl(var(--foreground))' }} title={item.value}>{item.value}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
