import { useState, useEffect } from 'react';
import type { Site } from '@/types/index.ts';
import { useSitesStore } from '@/store/sites.ts';
import { useToastStore } from '@/components/ui/Toast.tsx';
import Button from '@/components/ui/Button.tsx';
import Input from '@/components/ui/Input.tsx';
import Slider from '@/components/ui/Slider.tsx';
import FrequencySelector from './FrequencySelector.tsx';

interface SiteFormProps {
  editSite?: Site | null;
  pendingLocation?: { lat: number; lon: number } | null;
  onClose: () => void;
  onClearPending?: () => void;
  onCalculate?: () => void;
}

const TEMPLATES = {
  limesdr: {
    label: 'LimeSDR',
    style: 'purple',
    name: 'LimeSDR Mini',
    power: 20,
    gain: 2,
    frequency: 1800,
    height: 10,
    antennaType: 'omni' as const,
  },
  lowBBU: {
    label: 'Low BBU',
    style: 'green',
    name: 'Low Power BBU',
    power: 40,
    gain: 8,
    frequency: 1800,
    height: 20,
    antennaType: 'omni' as const,
  },
  highBBU: {
    label: 'High BBU',
    style: 'orange',
    name: 'High Power BBU',
    power: 43,
    gain: 15,
    frequency: 1800,
    height: 30,
    antennaType: 'sector' as const,
    azimuth: 0,
    beamwidth: 65,
  },
  urbanMacro: {
    label: 'Urban Macro',
    style: 'blue',
    name: 'Urban Macro Site',
    power: 43,
    gain: 18,
    frequency: 1800,
    height: 30,
    antennaType: 'sector' as const,
    azimuth: 0,
    beamwidth: 65,
  },
  ruralTower: {
    label: 'Rural Tower',
    style: 'emerald',
    name: 'Rural Tower',
    power: 46,
    gain: 8,
    frequency: 800,
    height: 50,
    antennaType: 'omni' as const,
  },
  smallCell: {
    label: 'Small Cell',
    style: 'cyan',
    name: 'Small Cell',
    power: 30,
    gain: 12,
    frequency: 2600,
    height: 6,
    antennaType: 'sector' as const,
    azimuth: 0,
    beamwidth: 90,
  },
  indoorDAS: {
    label: 'Indoor DAS',
    style: 'rose',
    name: 'Indoor DAS',
    power: 23,
    gain: 2,
    frequency: 2100,
    height: 3,
    antennaType: 'omni' as const,
  },
};

const TEMPLATE_COLORS: Record<string, string> = {
  purple: 'bg-purple-100 hover:bg-purple-200 text-purple-700 dark:bg-purple-900/30 dark:hover:bg-purple-900/50 dark:text-purple-300',
  green: 'bg-green-100 hover:bg-green-200 text-green-700 dark:bg-green-900/30 dark:hover:bg-green-900/50 dark:text-green-300',
  orange: 'bg-orange-100 hover:bg-orange-200 text-orange-700 dark:bg-orange-900/30 dark:hover:bg-orange-900/50 dark:text-orange-300',
  blue: 'bg-blue-100 hover:bg-blue-200 text-blue-700 dark:bg-blue-900/30 dark:hover:bg-blue-900/50 dark:text-blue-300',
  emerald: 'bg-emerald-100 hover:bg-emerald-200 text-emerald-700 dark:bg-emerald-900/30 dark:hover:bg-emerald-900/50 dark:text-emerald-300',
  cyan: 'bg-cyan-100 hover:bg-cyan-200 text-cyan-700 dark:bg-cyan-900/30 dark:hover:bg-cyan-900/50 dark:text-cyan-300',
  rose: 'bg-rose-100 hover:bg-rose-200 text-rose-700 dark:bg-rose-900/30 dark:hover:bg-rose-900/50 dark:text-rose-300',
};

export default function SiteForm({
  editSite,
  pendingLocation,
  onClose,
  onClearPending,
  onCalculate,
}: SiteFormProps) {
  const addSite = useSitesStore((s) => s.addSite);
  const updateSite = useSitesStore((s) => s.updateSite);
  const deleteSite = useSitesStore((s) => s.deleteSite);
  const addToast = useToastStore((s) => s.addToast);

  const [name, setName] = useState(editSite?.name ?? 'Station-1');
  const [lat, setLat] = useState(editSite?.lat ?? pendingLocation?.lat ?? 48.4647);
  const [lon, setLon] = useState(editSite?.lon ?? pendingLocation?.lon ?? 35.0462);
  const [power, setPower] = useState(editSite?.power ?? 43);
  const [gain, setGain] = useState(editSite?.gain ?? 8);
  const [frequency, setFrequency] = useState(editSite?.frequency ?? 1800);
  const [height, setHeight] = useState(editSite?.height ?? 30);
  const [antennaType, setAntennaType] = useState<'omni' | 'sector'>(
    editSite?.antennaType ?? 'omni'
  );
  const [azimuth, setAzimuth] = useState(editSite?.azimuth ?? 0);
  const [beamwidth, setBeamwidth] = useState(editSite?.beamwidth ?? 65);
  const [notes, setNotes] = useState(editSite?.notes ?? '');

  useEffect(() => {
    if (pendingLocation) {
      setLat(pendingLocation.lat);
      setLon(pendingLocation.lon);
    }
  }, [pendingLocation]);

  // Live-sync: update form when the edited site changes externally
  // (e.g., batch height adjustment, drag on map)
  useEffect(() => {
    if (editSite) {
      setHeight(editSite.height);
      setPower(editSite.power);
      setGain(editSite.gain);
      setName(editSite.name);
      setLat(editSite.lat);
      setLon(editSite.lon);
      setFrequency(editSite.frequency);
      setAntennaType(editSite.antennaType);
      setAzimuth(editSite.azimuth ?? 0);
      setBeamwidth(editSite.beamwidth ?? 65);
      setNotes(editSite.notes ?? '');
    }
  }, [editSite]);

  const applyTemplate = (key: keyof typeof TEMPLATES) => {
    const t = TEMPLATES[key];
    setName(t.name);
    setPower(t.power);
    setGain(t.gain);
    setFrequency(t.frequency);
    setHeight(t.height);
    setAntennaType(t.antennaType);
    if ('azimuth' in t) setAzimuth(t.azimuth);
    if ('beamwidth' in t) setBeamwidth(t.beamwidth);
    addToast(`Applied: ${t.name}`, 'success');
  };

  const handleSave = async () => {
    if (editSite) {
      await updateSite(editSite.id, {
        name,
        lat,
        lon,
        power,
        gain,
        frequency,
        height,
        antennaType,
        azimuth: antennaType === 'sector' ? azimuth : undefined,
        beamwidth: antennaType === 'sector' ? beamwidth : undefined,
        notes: notes || undefined,
      });
      addToast('Site updated', 'success');
    } else {
      await addSite({
        name,
        lat,
        lon,
        power,
        gain,
        frequency,
        height,
        antennaType,
        azimuth: antennaType === 'sector' ? azimuth : undefined,
        beamwidth: antennaType === 'sector' ? beamwidth : undefined,
        color: '',
        visible: true,
        notes: notes || undefined,
      });
      addToast('Site added', 'success');
    }
    onClearPending?.();
    onClose();
  };

  const handleSaveAndCalculate = async () => {
    await handleSave();
    // Trigger calculation after save
    if (onCalculate) {
      // Small delay to ensure store is updated
      setTimeout(() => onCalculate(), 50);
    }
  };

  const handleDelete = async () => {
    if (editSite) {
      await deleteSite(editSite.id);
      addToast(`"${editSite.name}" deleted`, 'info');
      onClearPending?.();
      onClose();
    }
  };

  return (
    <div className="bg-white dark:bg-dark-surface border border-gray-200 dark:border-dark-border rounded-lg shadow-lg overflow-y-auto max-h-[calc(100vh-120px)]">
      <div className="sticky top-0 bg-white dark:bg-dark-surface border-b border-gray-200 dark:border-dark-border px-4 py-3 flex items-center justify-between z-10">
        <h2 className="text-sm font-semibold text-gray-800 dark:text-dark-text">
          {editSite ? 'Edit Site' : 'New Site Configuration'}
        </h2>
        <button
          onClick={onClose}
          className="text-gray-400 hover:text-gray-600 dark:hover:text-dark-text text-lg min-w-[32px] min-h-[32px] flex items-center justify-center"
        >
          ×
        </button>
      </div>

      <div className="p-4 space-y-4">
        {/* Site name */}
        <Input
          label="Site Name"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Station-1"
        />

        {/* Coordinates */}
        <div className="space-y-1">
          <label className="text-sm font-medium text-gray-700 dark:text-dark-text">Coordinates</label>
          <div className="flex gap-2">
            <div className="flex-1">
              <input
                type="number"
                step="0.0001"
                value={lat}
                onChange={(e) => setLat(Number(e.target.value))}
                className="w-full px-3 py-1.5 border border-gray-300 dark:border-dark-border dark:bg-dark-bg dark:text-dark-text rounded-md text-sm
                  focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="Lat"
              />
            </div>
            <div className="flex-1">
              <input
                type="number"
                step="0.0001"
                value={lon}
                onChange={(e) => setLon(Number(e.target.value))}
                className="w-full px-3 py-1.5 border border-gray-300 dark:border-dark-border dark:bg-dark-bg dark:text-dark-text rounded-md text-sm
                  focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="Lon"
              />
            </div>
          </div>
        </div>

        {/* Separator */}
        <div className="border-t border-gray-200 dark:border-dark-border pt-2">
          <span className="text-xs font-semibold text-gray-500 dark:text-dark-muted uppercase tracking-wide">
            RF Parameters
          </span>
        </div>

        {/* Power */}
        <Slider
          label="Transmit Power (dBm)"
          value={power}
          min={10}
          max={50}
          unit="dBm"
          hint="LimeSDR 20, BBU 43, RRU 46"
          onChange={setPower}
        />

        {/* Gain */}
        <Slider
          label="Antenna Gain (dBi)"
          value={gain}
          min={0}
          max={25}
          unit="dBi"
          hint="Omni 2-8, Sector 15-18, Parabolic 20-25"
          onChange={setGain}
        />

        {/* Frequency */}
        <FrequencySelector value={frequency} onChange={setFrequency} />

        {/* Separator */}
        <div className="border-t border-gray-200 dark:border-dark-border pt-2">
          <span className="text-xs font-semibold text-gray-500 dark:text-dark-muted uppercase tracking-wide">
            Physical Parameters
          </span>
        </div>

        {/* Height */}
        <Slider
          label="Antenna Height (meters)"
          value={height}
          min={1}
          max={100}
          unit="m"
          hint="Height from ground to antenna center"
          onChange={setHeight}
        />

        {/* Antenna type */}
        <div className="space-y-2">
          <label className="text-sm font-medium text-gray-700 dark:text-dark-text">
            Antenna Type
          </label>
          <div className="flex gap-4">
            <label className="flex items-center gap-2 cursor-pointer min-h-[44px]">
              <input
                type="radio"
                name="antennaType"
                checked={antennaType === 'omni'}
                onChange={() => setAntennaType('omni')}
                className="accent-blue-600"
              />
              <span className="text-sm dark:text-dark-text">Omni</span>
            </label>
            <label className="flex items-center gap-2 cursor-pointer min-h-[44px]">
              <input
                type="radio"
                name="antennaType"
                checked={antennaType === 'sector'}
                onChange={() => setAntennaType('sector')}
                className="accent-blue-600"
              />
              <span className="text-sm dark:text-dark-text">Sector</span>
            </label>
          </div>
        </div>

        {/* Sector parameters - collapsible */}
        {antennaType === 'sector' && (
          <div className="bg-gray-50 dark:bg-dark-bg rounded-md p-3 space-y-3 border border-gray-200 dark:border-dark-border">
            <Slider
              label="Azimuth (degrees)"
              value={azimuth}
              min={0}
              max={360}
              unit="°"
              onChange={setAzimuth}
            />
            <Slider
              label="Beamwidth (degrees)"
              value={beamwidth}
              min={30}
              max={120}
              unit="°"
              onChange={setBeamwidth}
            />
          </div>
        )}

        {/* Separator */}
        <div className="border-t border-gray-200 dark:border-dark-border pt-2">
          <span className="text-xs font-semibold text-gray-500 dark:text-dark-muted uppercase tracking-wide">
            Notes
          </span>
        </div>

        {/* Notes */}
        <div className="space-y-1">
          <label className="text-sm font-medium text-gray-700 dark:text-dark-text">
            Equipment / Notes (optional)
          </label>
          <textarea
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            placeholder="e.g., ZTE B8200 BBU + custom omni antenna"
            rows={2}
            className="w-full px-3 py-2 border border-gray-300 dark:border-dark-border dark:bg-dark-bg dark:text-dark-text rounded-md text-sm
              focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500
              resize-none"
          />
        </div>

        {/* Quick Templates */}
        <div className="space-y-1">
          <label className="text-xs font-semibold text-gray-500 dark:text-dark-muted uppercase tracking-wide">
            Quick Templates
          </label>
          <div className="flex gap-2 flex-wrap">
            {Object.entries(TEMPLATES).map(([key, t]) => (
              <button
                key={key}
                type="button"
                onClick={() => applyTemplate(key as keyof typeof TEMPLATES)}
                className={`px-3 py-1.5 rounded text-xs font-medium transition-colors min-h-[32px]
                  ${TEMPLATE_COLORS[t.style] ?? TEMPLATE_COLORS.blue}`}
              >
                {t.label}
              </button>
            ))}
          </div>
        </div>

        {/* Actions */}
        <div className="flex gap-2 pt-2">
          <Button onClick={handleSaveAndCalculate} className="flex-1">
            Save & Calculate
          </Button>
          <Button variant="secondary" onClick={handleSave}>
            Save Only
          </Button>
          {editSite && (
            <Button variant="danger" onClick={handleDelete}>
              Del
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}
