import React, { useState, useEffect } from 'react';
import { Save, Loader2, MapPin, Plus, Trash2 } from 'lucide-react';
import { SiteSettings } from '../types';
import { api } from '../lib/api';

interface DeliveryZone {
  id: string;
  name: string;
  charge: number;
}

interface DeliveryLocationsEditorProps {
  settings: SiteSettings;
  updateSettings: (newSettings: Partial<SiteSettings>) => void;
  showToast: (msg: string, type: 'success' | 'error') => void;
}

const DeliveryLocationsEditor: React.FC<DeliveryLocationsEditorProps> = ({
  settings,
  updateSettings,
  showToast
}) => {
  const [isSaving, setIsSaving] = useState(false);
  const [zones, setZones] = useState<DeliveryZone[]>([]);

  useEffect(() => {
    if (settings.deliveryZones && settings.deliveryZones.length > 0) {
      setZones(settings.deliveryZones);
    } else {
      // Default fallback if empty
      setZones([
        { id: 'inside_ctg', name: 'inside Dhaka', charge: 70 },
        { id: 'outside_ctg', name: 'Outside Dhaka', charge: 130 }
      ]);
    }
  }, [settings.deliveryZones]);

  const handleAddZone = () => {
    const newId = 'zone_' + Math.random().toString(36).substr(2, 9);
    setZones([...zones, { id: newId, name: '', charge: 0 }]);
  };

  const handleRemoveZone = (id: string) => {
    setZones(zones.filter(z => z.id !== id));
  };

  const handleZoneChange = (id: string, field: keyof DeliveryZone, value: string | number) => {
    setZones(zones.map(z => {
      if (z.id === id) {
        return { ...z, [field]: value };
      }
      return z;
    }));
  };

  const handleSave = async () => {
    // Validate
    if (zones.some(z => !z.name.trim())) {
      showToast('All delivery areas must have a name.', 'error');
      return;
    }

    setIsSaving(true);
    try {
      const token = localStorage.getItem('tenant_token');
      const response = await fetch('/api/admin/settings', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(token ? { 'X-Tenant-Token': token } : {})
        },
        body: JSON.stringify({ deliveryZones: zones })
      });

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

      updateSettings({ deliveryZones: zones });
      showToast('Delivery locations sorted!', 'success');
    } catch (err: any) {
      showToast(err.message, 'error');
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div className="max-w-4xl mx-auto space-y-6 pb-20 fade-in">
      {/* Header */}
      <div className="mb-8">
        <h2 className="text-3xl font-black text-slate-900 tracking-tight flex items-center gap-3">
          <div className="w-12 h-12 bg-red-100 text-red-600 rounded-2xl flex items-center justify-center shadow-inner">
            <MapPin size={24} />
          </div>
          Delivery Locations
        </h2>
        <p className="text-slate-500 font-medium mt-2">Manage your delivery zones and and specify their charges. These will dynamically appear on your checkout popup.</p>
      </div>

      <div className="bg-white rounded-3xl p-8 shadow-xl border border-slate-100 space-y-6 relative overflow-hidden">
        {/* Abstract shape decoration */}
        <div className="absolute top-0 right-0 w-64 h-64 bg-red-50 rounded-full blur-3xl -z-10 opacity-60 translate-x-1/2 -translate-y-1/2"></div>

        <div className="flex items-center justify-between">
          <h3 className="text-xl font-bold text-slate-800">Dynamic Delivery Pricing Map</h3>
          <button
            onClick={handleAddZone}
            className="px-4 py-2 bg-slate-900 hover:bg-slate-800 text-white font-bold rounded-xl text-sm flex items-center gap-2 transition-all active:scale-95 shadow-md shadow-slate-900/20"
          >
            <Plus size={16} /> Add New Location
          </button>
        </div>

        <div className="space-y-4">
          {zones.map((zone, index) => (
            <div key={zone.id} className="grid grid-cols-1 md:grid-cols-12 gap-4 items-end bg-slate-50 p-4 rounded-2xl border border-slate-100 hover:border-red-200 transition-colors">
              <div className="md:col-span-1 flex items-center justify-center font-black text-slate-300 text-xl">
                #{index + 1}
              </div>
              <div className="md:col-span-6">
                <label className="text-xs font-black text-slate-500 mb-1 block uppercase tracking-wider">Area Name</label>
                <input
                  type="text"
                  value={zone.name}
                  onChange={(e) => handleZoneChange(zone.id, 'name', e.target.value)}
                  className="w-full px-4 py-3 bg-white border-2 border-slate-200 focus:border-red-600 rounded-xl font-bold transition-all text-slate-900 placeholder:text-slate-300"
                  placeholder="e.g. Inside Dhaka"
                />
              </div>
              <div className="md:col-span-4">
                <label className="text-xs font-black text-slate-500 mb-1 block uppercase tracking-wider">Charge (৳)</label>
                <input
                  type="number"
                  value={zone.charge}
                  onChange={(e) => handleZoneChange(zone.id, 'charge', Number(e.target.value))}
                  className="w-full px-4 py-3 bg-white border-2 border-slate-200 focus:border-red-600 rounded-xl font-bold transition-all text-slate-900"
                  min="0"
                />
              </div>
              <div className="md:col-span-1 flex justify-end pb-1">
                <button
                  onClick={() => handleRemoveZone(zone.id)}
                  disabled={zones.length === 1}
                  className="w-12 h-12 bg-red-50 text-red-600 hover:bg-red-600 hover:text-white rounded-xl flex items-center justify-center transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-sm font-black"
                >
                  <Trash2 size={20} />
                </button>
              </div>
            </div>
          ))}

          {zones.length === 0 && (
            <div className="text-center py-10 text-slate-400 font-medium bg-slate-50 rounded-2xl border-2 border-dashed border-slate-200">
              No delivery locations configured. Add one.
            </div>
          )}
        </div>

        <div className="pt-6 border-t border-slate-100 flex justify-end">
          <button
            onClick={handleSave}
            disabled={isSaving}
            className="px-8 py-4 bg-red-600 hover:bg-red-700 text-white rounded-xl font-black flex items-center gap-2 transition-all active:scale-95 shadow-xl shadow-red-600/30 disabled:opacity-50"
          >
            {isSaving ? <Loader2 size={20} className="animate-spin" /> : <Save size={20} />}
            Save Delivery Pricing
          </button>
        </div>
      </div>
    </div>
  );
};

export default DeliveryLocationsEditor;
