'use client';

import { useState, useEffect } from 'react';
import { X, Clock, Save, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';

interface RouteData {
  id: string;
  twilio_number: string;
  twilio_number_sid: string | null;
  closebot_source_id: string;
  closebot_bot_id: string | null;
  bot_name: string | null;
  greeting_message: string | null;
  after_hours_reply: string | null;
  business_hours_json: string | null;
  max_concurrent: number;
  active: number;
  created_at: string;
  updated_at: string;
}

interface RouteConfigModalProps {
  route: RouteData;
  onClose: () => void;
  onSaved: (updated: RouteData) => void;
}

interface BusinessHours {
  [day: string]: { start: string; end: string } | undefined;
}

const DAYS = [
  { key: 'mon', label: 'Mon' },
  { key: 'tue', label: 'Tue' },
  { key: 'wed', label: 'Wed' },
  { key: 'thu', label: 'Thu' },
  { key: 'fri', label: 'Fri' },
  { key: 'sat', label: 'Sat' },
  { key: 'sun', label: 'Sun' },
];

const DEFAULT_HOURS: BusinessHours = {
  mon: { start: '09:00', end: '17:00' },
  tue: { start: '09:00', end: '17:00' },
  wed: { start: '09:00', end: '17:00' },
  thu: { start: '09:00', end: '17:00' },
  fri: { start: '09:00', end: '17:00' },
};

function parseBusinessHours(json: string | null): BusinessHours {
  if (!json) return DEFAULT_HOURS;
  try {
    return JSON.parse(json);
  } catch {
    return DEFAULT_HOURS;
  }
}

function formatTime12(time24: string): string {
  const [h, m] = time24.split(':').map(Number);
  const period = h >= 12 ? 'PM' : 'AM';
  const hour12 = h === 0 ? 12 : h > 12 ? h - 12 : h;
  return `${hour12}:${m.toString().padStart(2, '0')} ${period}`;
}

function summarizeHours(hours: BusinessHours): string {
  const activeDays = DAYS.filter(d => hours[d.key]);
  if (activeDays.length === 0) return 'No business hours set';

  // Group consecutive days with same hours
  const groups: { days: string[]; start: string; end: string }[] = [];

  for (const day of activeDays) {
    const h = hours[day.key]!;
    const lastGroup = groups[groups.length - 1];
    if (lastGroup && lastGroup.start === h.start && lastGroup.end === h.end) {
      lastGroup.days.push(day.label);
    } else {
      groups.push({ days: [day.label], start: h.start, end: h.end });
    }
  }

  return groups
    .map(g => {
      const dayRange = g.days.length > 2
        ? `${g.days[0]}-${g.days[g.days.length - 1]}`
        : g.days.join(', ');
      return `${dayRange}: ${formatTime12(g.start)} - ${formatTime12(g.end)}`;
    })
    .join(' · ');
}

export default function RouteConfigModal({ route, onClose, onSaved }: RouteConfigModalProps) {
  const [greeting, setGreeting] = useState(route.greeting_message || '');
  const [afterHours, setAfterHours] = useState(
    route.after_hours_reply || 'Thanks for reaching out! We are currently offline and will get back to you during business hours.'
  );
  const [businessHours, setBusinessHours] = useState<BusinessHours>(
    parseBusinessHours(route.business_hours_json)
  );
  const [maxConcurrent, setMaxConcurrent] = useState(route.max_concurrent || 50);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Prevent body scroll
  useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

  function toggleDay(dayKey: string) {
    setBusinessHours(prev => {
      const updated = { ...prev };
      if (updated[dayKey]) {
        delete updated[dayKey];
      } else {
        updated[dayKey] = { start: '09:00', end: '17:00' };
      }
      return updated;
    });
  }

  async function handleSave() {
    setSaving(true);
    setError(null);

    try {
      const res = await fetch(`/api/routes/${route.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          greeting_message: greeting || null,
          after_hours_reply: afterHours || null,
          business_hours_json: businessHours,
          max_concurrent: maxConcurrent,
        }),
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || 'Failed to save');
      }

      const updated = await res.json();
      onSaved(updated);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save');
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/60 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Modal */}
      <div className="relative w-full max-w-2xl max-h-[90vh] overflow-y-auto mx-4 rounded-2xl border border-slate-700/60 bg-[#131d2e] shadow-2xl shadow-black/40">
        {/* Header */}
        <div className="sticky top-0 z-10 flex items-center justify-between border-b border-slate-700/50 bg-[#131d2e]/95 backdrop-blur-sm px-6 py-4">
          <div>
            <h2 className="text-lg font-bold text-white">Route Configuration</h2>
            <p className="text-sm text-cyan-400 font-medium mt-0.5">{route.bot_name}</p>
          </div>
          <button
            onClick={onClose}
            className="flex h-9 w-9 items-center justify-center rounded-lg border border-slate-700/50 text-slate-400 hover:text-white hover:bg-slate-700/50 transition-colors"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        <div className="p-6 space-y-6">
          {/* Greeting Message Override */}
          <div>
            <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">
              Greeting Message Override
            </label>
            <textarea
              value={greeting}
              onChange={(e) => setGreeting(e.target.value)}
              placeholder="Enter a custom greeting message that will be sent when a new conversation starts..."
              rows={3}
              className="w-full rounded-lg border border-slate-700/50 bg-slate-800/50 px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none transition-colors focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 resize-none"
            />
            <p className="text-[11px] text-slate-600 mt-1">Leave blank to use the bot&apos;s default greeting</p>
          </div>

          {/* After-Hours Auto-Reply */}
          <div>
            <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">
              After-Hours Auto-Reply Text
            </label>
            <textarea
              value={afterHours}
              onChange={(e) => setAfterHours(e.target.value)}
              placeholder="Message sent when someone texts outside business hours..."
              rows={3}
              className="w-full rounded-lg border border-slate-700/50 bg-slate-800/50 px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none transition-colors focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 resize-none"
            />
          </div>

          {/* Business Hours Schedule */}
          <div>
            <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-3">
              <Clock className="inline h-3.5 w-3.5 mr-1.5 -mt-0.5" />
              Business Hours Schedule
            </label>

            {/* Day-of-week grid */}
            <div className="flex gap-2 mb-3">
              {DAYS.map(day => {
                const isActive = !!businessHours[day.key];
                return (
                  <button
                    key={day.key}
                    onClick={() => toggleDay(day.key)}
                    className={cn(
                      'flex-1 py-2 rounded-lg text-xs font-bold uppercase tracking-wider transition-all duration-200 border',
                      isActive
                        ? 'bg-cyan-500/15 text-cyan-400 border-cyan-500/30 shadow-[0_0_10px_rgba(34,211,238,0.1)]'
                        : 'bg-slate-800/30 text-slate-600 border-slate-700/30 hover:border-slate-600/50 hover:text-slate-400'
                    )}
                  >
                    {day.label}
                  </button>
                );
              })}
            </div>

            {/* Hours summary */}
            <div className="rounded-lg border border-slate-700/30 bg-slate-800/30 px-4 py-3">
              <p className="text-sm text-slate-300">{summarizeHours(businessHours)}</p>
            </div>

            <button className="mt-2 text-xs text-cyan-500 hover:text-cyan-400 font-medium transition-colors">
              + Add Exception
            </button>
          </div>

          {/* Max Concurrent Conversations */}
          <div>
            <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-3">
              Max Concurrent Conversations
            </label>
            <div className="flex items-center gap-4">
              <input
                type="range"
                min={1}
                max={100}
                value={maxConcurrent}
                onChange={(e) => setMaxConcurrent(Number(e.target.value))}
                className="flex-1 h-2 rounded-full bg-slate-700/50 appearance-none cursor-pointer accent-cyan-500
                  [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:w-5
                  [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-cyan-400
                  [&::-webkit-slider-thumb]:shadow-[0_0_8px_rgba(34,211,238,0.4)]
                  [&::-webkit-slider-thumb]:border-2 [&::-webkit-slider-thumb]:border-cyan-300"
              />
              <div className="flex h-10 w-16 items-center justify-center rounded-lg border border-slate-700/50 bg-slate-800/50">
                <span className="text-sm font-bold text-white num">{maxConcurrent}</span>
              </div>
            </div>
            <p className="text-[11px] text-slate-600 mt-1.5">
              Limit the number of active conversations this route handles simultaneously
            </p>
          </div>

          {/* Error */}
          {error && (
            <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3">
              <p className="text-sm text-red-400">{error}</p>
            </div>
          )}

          {/* Actions */}
          <div className="flex items-center justify-between pt-2">
            <button
              onClick={onClose}
              className="rounded-lg border border-slate-700/50 px-4 py-2.5 text-sm font-medium text-slate-400 hover:text-slate-200 hover:bg-slate-800/50 transition-colors"
            >
              Close Configuration
            </button>
            <button
              onClick={handleSave}
              disabled={saving}
              className={cn(
                'flex items-center gap-2 rounded-lg px-5 py-2.5 text-sm font-semibold transition-all duration-200',
                'bg-cyan-500 text-white hover:bg-cyan-400 shadow-[0_0_20px_rgba(34,211,238,0.2)]',
                'disabled:opacity-50 disabled:cursor-not-allowed'
              )}
            >
              {saving ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Save className="h-4 w-4" />
              )}
              {saving ? 'Saving...' : 'Save Changes'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
