'use client';

import { useState, useEffect } from 'react';
import { Save } from 'lucide-react';
import { systemConfigApi } from '@/lib/api';

type Tab = 'general' | 'payment' | 'integrations' | 'configurations';

export default function SettingsPage() {
  const [activeTab, setActiveTab] = useState<Tab>('general');
  const [seatHoldMinutes, setSeatHoldMinutes] = useState('5');
  const [bookingPayWindow, setBookingPayWindow] = useState('120');
  const [reschedulePayWindow, setReschedulePayWindow] = useState('120');
  const [upgradePayWindow, setUpgradePayWindow] = useState('120');
  const [holdCutoffHours, setHoldCutoffHours] = useState('2');
  const [boardingWindowHours, setBoardingWindowHours] = useState('4');
  const [throttleAuthLimit, setThrottleAuthLimit] = useState('5');
  const [throttleStrictLimit, setThrottleStrictLimit] = useState('20');
  const [throttleDefaultLimit, setThrottleDefaultLimit] = useState('100');
  const [configLoading, setConfigLoading] = useState(false);
  const [configSaving, setConfigSaving] = useState(false);
  const [configMessage, setConfigMessage] = useState('');

  useEffect(() => {
    if (activeTab !== 'configurations') return;
    setConfigLoading(true);
    systemConfigApi.getAll()
      .then((data) => {
        if (data?.seat_hold_duration_minutes) setSeatHoldMinutes(data.seat_hold_duration_minutes);
        if (data?.booking_payment_window_minutes) setBookingPayWindow(data.booking_payment_window_minutes);
        if (data?.reschedule_payment_window_minutes) setReschedulePayWindow(data.reschedule_payment_window_minutes);
        if (data?.upgrade_payment_window_minutes) setUpgradePayWindow(data.upgrade_payment_window_minutes);
        if (data?.hold_cutoff_hours_before_departure) setHoldCutoffHours(data.hold_cutoff_hours_before_departure);
        if (data?.boarding_window_hours_before_departure) setBoardingWindowHours(data.boarding_window_hours_before_departure);
        if (data?.throttle_auth_limit) setThrottleAuthLimit(data.throttle_auth_limit);
        if (data?.throttle_strict_limit) setThrottleStrictLimit(data.throttle_strict_limit);
        if (data?.throttle_default_limit) setThrottleDefaultLimit(data.throttle_default_limit);
      })
      .catch(() => {})
      .finally(() => setConfigLoading(false));
  }, [activeTab]);

  const saveConfigurations = async () => {
    setConfigSaving(true);
    setConfigMessage('');
    try {
      await systemConfigApi.update({
        seat_hold_duration_minutes: seatHoldMinutes,
        booking_payment_window_minutes: bookingPayWindow,
        reschedule_payment_window_minutes: reschedulePayWindow,
        upgrade_payment_window_minutes: upgradePayWindow,
        hold_cutoff_hours_before_departure: holdCutoffHours,
        boarding_window_hours_before_departure: boardingWindowHours,
        throttle_auth_limit: throttleAuthLimit,
        throttle_strict_limit: throttleStrictLimit,
        throttle_default_limit: throttleDefaultLimit,
      });
      setConfigMessage('Saved successfully.');
    } catch {
      setConfigMessage('Failed to save.');
    } finally {
      setConfigSaving(false);
    }
  };

  const tabs: { id: Tab; label: string }[] = [
    { id: 'general', label: 'General' },
    { id: 'configurations', label: 'Configurations' },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Settings</h1>
          <p className="text-muted-foreground">Manage system settings and configurations</p>
        </div>
        {activeTab !== 'configurations' && (
          <button className="btn btn-primary flex items-center gap-2">
            <Save className="h-4 w-4" />
            Save Changes
          </button>
        )}
      </div>

      <div className="flex gap-2 border-b border-border">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`px-4 py-2 font-medium ${activeTab === tab.id ? 'border-b-2 border-primary text-primary' : 'text-muted-foreground'}`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {activeTab === 'general' && (
        <div className="card space-y-4">
          <div>
            <label className="label">Platform Name</label>
            <input type="text" className="input" defaultValue="EDR Passenger Platform" />
          </div>
          <div>
            <label className="label">Support Email</label>
            <input type="email" className="input" defaultValue="edr_@edrsc.com" />
          </div>
          <div>
            <label className="label">Support Phone</label>
            <input type="tel" className="input" defaultValue="+2519546" />
          </div>
          <div>
            <label className="label">Default Currency</label>
            <select className="input">
              <option>ETB - Ethiopian Birr</option>
              <option>DJF - Djiboutian Franc</option>
              <option>USD - US Dollar</option>
            </select>
          </div>
        </div>
      )}
      

      {activeTab === 'configurations' && (
        <div className="card space-y-6">
          <h3 className="text-lg font-semibold text-foreground">Rate Limiting (requests / minute / IP)</h3>
          {!configLoading && (
            <div className="max-w-sm space-y-4">
              <div className="space-y-2">
                <label className="label" htmlFor="throttle-auth">Auth endpoints limit</label>
                <input
                  id="throttle-auth"
                  type="number" min="1" className="input"
                  value={throttleAuthLimit}
                  onChange={(e) => setThrottleAuthLimit(e.target.value)}
                />
                <p className="text-xs text-muted-foreground">Login, register, OTP. Default: 5.</p>
              </div>
              <div className="space-y-2">
                <label className="label" htmlFor="throttle-strict">Strict endpoints limit</label>
                <input
                  id="throttle-strict"
                  type="number" min="1" className="input"
                  value={throttleStrictLimit}
                  onChange={(e) => setThrottleStrictLimit(e.target.value)}
                />
                <p className="text-xs text-muted-foreground">Sensitive operations. Default: 20.</p>
              </div>
              <div className="space-y-2">
                <label className="label" htmlFor="throttle-default">Default endpoints limit</label>
                <input
                  id="throttle-default"
                  type="number" min="1" className="input"
                  value={throttleDefaultLimit}
                  onChange={(e) => setThrottleDefaultLimit(e.target.value)}
                />
                <p className="text-xs text-muted-foreground">All other endpoints including search. Default: 100.</p>
              </div>
            </div>
          )}
          <h3 className="text-lg font-semibold text-foreground">Payment Windows (minutes)</h3>
          <p className="text-xs text-muted-foreground -mt-4">
            How long a payer has before the request expires and the held seat is released. The
            check-in cutoff is still the hard limit — a longer window can never allow payment after
            boarding closes.
          </p>
          <div className="max-w-sm space-y-4">
              <div className="space-y-2">
                <label className="label" htmlFor="booking-pay-window">New booking</label>
                <input
                  id="booking-pay-window"
                  type="number" min="1" className="input"
                  value={bookingPayWindow}
                  onChange={(e) => setBookingPayWindow(e.target.value)}
                />
                <p className="text-xs text-muted-foreground">Time to pay for a new booking before it is auto-cancelled. Default: 120.</p>
              </div>
              <div className="space-y-2">
                <label className="label" htmlFor="reschedule-pay-window">Reschedule</label>
                <input
                  id="reschedule-pay-window"
                  type="number" min="1" className="input"
                  value={reschedulePayWindow}
                  onChange={(e) => setReschedulePayWindow(e.target.value)}
                />
                <p className="text-xs text-muted-foreground">Time to pay a reschedule charge. Default: 120.</p>
              </div>
              <div className="space-y-2">
                <label className="label" htmlFor="upgrade-pay-window">Fare upgrade</label>
                <input
                  id="upgrade-pay-window"
                  type="number" min="1" className="input"
                  value={upgradePayWindow}
                  onChange={(e) => setUpgradePayWindow(e.target.value)}
                />
                <p className="text-xs text-muted-foreground">Time to pay a fare-class upgrade. Default: 120.</p>
              </div>
          </div>
          <h3 className="text-lg font-semibold text-foreground">Seat Booking</h3>
          {configLoading ? (
            <p className="text-sm text-muted-foreground">Loading...</p>
          ) : (
            <>
              <div className="max-w-sm space-y-2">
                <label className="label" htmlFor="hold-duration">
                  Seat Hold Duration (minutes)
                </label>
                <input
                  id="hold-duration"
                  type="number"
                  min="1"
                  max="60"
                  className="input"
                  value={seatHoldMinutes}
                  onChange={(e) => setSeatHoldMinutes(e.target.value)}
                />
                <p className="text-xs text-muted-foreground">
                  How long a seat hold remains active before it expires automatically. Default: 5 minutes.
                </p>
              </div>
              <div className="max-w-sm space-y-2">
                <label className="label" htmlFor="hold-cutoff">
                  Hold Cutoff Before Departure (hours)
                </label>
                <input
                  id="hold-cutoff"
                  type="number"
                  min="0"
                  max="24"
                  className="input"
                  value={holdCutoffHours}
                  onChange={(e) => setHoldCutoffHours(e.target.value)}
                />
                <p className="text-xs text-muted-foreground">
                  Seat holds are rejected when this many hours or fewer remain before departure. Default: 2 hours.
                </p>
              </div>
              <div className="max-w-sm space-y-2">
                <label className="label" htmlFor="boarding-window">
                  Boarding Window Before Departure (hours)
                </label>
                <input
                  id="boarding-window"
                  type="number"
                  min="1"
                  max="24"
                  className="input"
                  value={boardingWindowHours}
                  onChange={(e) => setBoardingWindowHours(e.target.value)}
                />
                <p className="text-xs text-muted-foreground">
                  Boarding opens this many hours before departure and closes exactly at departure time. Default: 4 hours.
                </p>
              </div>
            </>
          )}
          <div className="flex items-center gap-3">
            <button
              className="btn btn-primary flex items-center gap-2"
              onClick={saveConfigurations}
              disabled={configSaving || configLoading}
            >
              <Save className="h-4 w-4" />
              {configSaving ? 'Saving...' : 'Save Changes'}
            </button>
            {configMessage && (
              <span className="text-sm text-muted-foreground">{configMessage}</span>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
