'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Plus, Edit, Trash2, Loader2, X } from 'lucide-react';
import toast from 'react-hot-toast';
import {
  fetchShippingMethod,
  updateShippingMethod,
  type ShippingMethod,
} from '@/lib/services/shipping-methods';
import {
  createShippingRule,
  deleteShippingRule,
  updateShippingRule,
  fetchShippingRules,
  type ShippingRule as ShippingRuleType,
} from '@/lib/services/shipping';
import {
  fetchShippingRegions,
  updateShippingRegions,
  type ShippingRegion,
} from '@/lib/services/shipping-regions';
import {
  fetchCountries,
  fetchStates,
  type Country,
  type State,
} from '@/lib/services/countries';

type ModalMode = 'create' | 'edit';

const WEIGHT_UNITS = ['kg', 'lbs', 'g', 'oz'] as const;
const CURRENCIES = ['USD', 'PKR', 'GBP', 'EUR'] as const;

export default function EditShippingMethod() {
  const params = useParams();
  const router = useRouter();
  const methodId = params?.id as string;

  const [method, setMethod] = useState<ShippingMethod | null>(null);
  const [rules, setRules] = useState<ShippingRuleType[]>([]);
  const [regions, setRegions] = useState<ShippingRegion[]>([]);
  const [countries, setCountries] = useState<Country[]>([]);
  const [allStates, setAllStates] = useState<State[]>([]);
  const [selectedCountryIds, setSelectedCountryIds] = useState<string[]>([]);
  const [selectedStateIds, setSelectedStateIds] = useState<string[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isLoadingRegions, setIsLoadingRegions] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [methodFormData, setMethodFormData] = useState({
    name: '',
    description: '',
    isActive: true,
    order: '0',
  });
  const [isSavingMethod, setIsSavingMethod] = useState(false);
  const [ruleModalMode, setRuleModalMode] = useState<ModalMode | null>(null);
  const [selectedRule, setSelectedRule] = useState<ShippingRuleType | null>(null);
  const [ruleFormData, setRuleFormData] = useState({
    name: '',
    minWeight: '',
    maxWeight: '',
    cost: '',
    currency: 'USD',
    weightUnit: 'kg',
    priority: '0',
    isActive: true,
  });
  const [isSubmittingRule, setIsSubmittingRule] = useState(false);

  useEffect(() => {
    let isMounted = true;

    async function loadData() {
      if (!methodId) {
        setError('Shipping method ID is required');
        setIsLoading(false);
        return;
      }

      setIsLoading(true);
      setError(null);

      try {
        const [methodData, rulesData, regionsData, countriesData, statesData] = await Promise.all([
          fetchShippingMethod(methodId),
          fetchShippingRules(),
          fetchShippingRegions(methodId),
          fetchCountries(),
          fetchStates(),
        ]);

        if (!isMounted) return;

        setMethod(methodData);
        setMethodFormData({
          name: methodData.name,
          description: methodData.description || '',
          isActive: methodData.isActive,
          order: methodData.order.toString(),
        });

        // Filter rules for this shipping method
        const methodRules = rulesData.filter((rule) => rule.shippingMethodId === methodId);
        setRules(methodRules);

        // Set regions
        setRegions(regionsData);
        setCountries(countriesData.filter((c) => c.isActive));
        setAllStates(statesData.filter((s) => s.isActive));

        // Extract selected country and state IDs
        const countryIds = regionsData.filter((r) => r.type === 'country' && r.countryId).map((r) => r.countryId!);
        const stateIds = regionsData.filter((r) => r.type === 'state' && r.stateId).map((r) => r.stateId!);
        setSelectedCountryIds(countryIds);
        setSelectedStateIds(stateIds);
      } catch (err) {
        console.error(err);
        if (isMounted) {
          setError('Unable to load shipping method');
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    }

    void loadData();

    return () => {
      isMounted = false;
    };
  }, [methodId]);

  const handleSaveMethod = async () => {
    if (!method) return;

    if (!methodFormData.name.trim()) {
      setError('Method name is required');
      toast.error('Method name is required');
      return;
    }

    try {
      setIsSavingMethod(true);
      setError(null);

      const updatedMethod = await updateShippingMethod(method.id, {
        name: methodFormData.name.trim(),
        description: methodFormData.description.trim() || null,
        isActive: methodFormData.isActive,
        order: Number.parseInt(methodFormData.order, 10) || 0,
      });

      setMethod(updatedMethod);
      toast.success('Shipping method updated successfully');
    } catch (err) {
      console.error(err);
      setError('Unable to update shipping method');
      toast.error('Unable to update shipping method');
    } finally {
      setIsSavingMethod(false);
    }
  };

  const handleOpenRuleModal = (mode: ModalMode, rule?: ShippingRuleType) => {
    setRuleModalMode(mode);
    if (mode === 'edit' && rule) {
      setSelectedRule(rule);
      setRuleFormData({
        name: rule.name,
        minWeight: rule.minWeight.toString(),
        maxWeight: rule.maxWeight?.toString() || '',
        cost: rule.cost.toString(),
        currency: rule.currency,
        weightUnit: rule.weightUnit,
        priority: rule.priority.toString(),
        isActive: rule.isActive,
      });
    } else {
      setSelectedRule(null);
      setRuleFormData({
        name: '',
        minWeight: '',
        maxWeight: '',
        cost: '',
        currency: 'USD',
        weightUnit: 'kg',
        priority: '0',
        isActive: true,
      });
    }
  };

  const handleCloseRuleModal = () => {
    setRuleModalMode(null);
    setSelectedRule(null);
    setRuleFormData({
      name: '',
      minWeight: '',
      maxWeight: '',
      cost: '',
      currency: 'USD',
      weightUnit: 'kg',
      priority: '0',
      isActive: true,
    });
  };

  const handleSubmitRule = async () => {
    if (!method) return;

    if (!ruleFormData.name.trim()) {
      toast.error('Rule name is required');
      return;
    }

    const minWeight = Number.parseFloat(ruleFormData.minWeight);
    if (Number.isNaN(minWeight) || minWeight < 0) {
      toast.error('Minimum weight must be a valid number >= 0');
      return;
    }

    const maxWeight = ruleFormData.maxWeight ? Number.parseFloat(ruleFormData.maxWeight) : null;
    if (maxWeight !== null && (Number.isNaN(maxWeight) || maxWeight <= minWeight)) {
      toast.error('Maximum weight must be greater than minimum weight');
      return;
    }

    const cost = Number.parseFloat(ruleFormData.cost);
    if (Number.isNaN(cost) || cost < 0) {
      toast.error('Cost must be a valid number >= 0');
      return;
    }

    const priority = Number.parseInt(ruleFormData.priority, 10) || 0;

    try {
      setIsSubmittingRule(true);

      const payload = {
        shippingMethodId: method.id,
        name: ruleFormData.name.trim(),
        minWeight,
        maxWeight,
        cost,
        currency: ruleFormData.currency,
        weightUnit: ruleFormData.weightUnit,
        priority,
        isActive: ruleFormData.isActive,
      };

      if (ruleModalMode === 'create') {
        const newRule = await createShippingRule(payload);
        setRules((prev) => [...prev, newRule].sort((a, b) => b.priority - a.priority || a.minWeight - b.minWeight));
        toast.success('Shipping rule created successfully');
      } else if (ruleModalMode === 'edit' && selectedRule) {
        const updatedRule = await updateShippingRule(selectedRule.id, payload);
        setRules((prev) =>
          prev.map((rule) => (rule.id === selectedRule.id ? updatedRule : rule)).sort((a, b) => b.priority - a.priority || a.minWeight - b.minWeight)
        );
        toast.success('Shipping rule updated successfully');
      }

      handleCloseRuleModal();
    } catch (err) {
      console.error(err);
      toast.error('Unable to save shipping rule');
    } finally {
      setIsSubmittingRule(false);
    }
  };

  const handleDeleteRule = async (rule: ShippingRuleType) => {
    if (!confirm(`Delete shipping rule "${rule.name}"?`)) {
      return;
    }

    try {
      await deleteShippingRule(rule.id);
      setRules((prev) => prev.filter((r) => r.id !== rule.id));
      toast.success('Shipping rule deleted successfully');
    } catch (err) {
      console.error(err);
      toast.error('Unable to delete shipping rule');
    }
  };

  const toggleRuleActive = async (rule: ShippingRuleType) => {
    try {
      const updatedRule = await updateShippingRule(rule.id, {
        isActive: !rule.isActive,
      });
      setRules((prev) =>
        prev.map((r) => (r.id === rule.id ? updatedRule : r))
      );
      toast.success(`Shipping rule ${updatedRule.isActive ? 'enabled' : 'disabled'}`);
    } catch (err) {
      console.error(err);
      toast.error('Unable to update shipping rule');
    }
  };

  const handleSaveRegions = async () => {
    if (!methodId) return;

    try {
      setIsLoadingRegions(true);
      setError(null);

      const regionsToSave: Array<{
        type: 'country' | 'state';
        countryId?: string;
        stateId?: string;
      }> = [];

      // Add country regions
      selectedCountryIds.forEach((countryId) => {
        regionsToSave.push({
          type: 'country',
          countryId,
        });
      });

      // Add state regions
      selectedStateIds.forEach((stateId) => {
        regionsToSave.push({
          type: 'state',
          stateId,
        });
      });

      const updatedRegions = await updateShippingRegions({
        shippingMethodId: methodId,
        regions: regionsToSave,
      });

      setRegions(updatedRegions);
      toast.success('Shipping regions updated successfully');
    } catch (err) {
      console.error(err);
      setError('Unable to update shipping regions');
      toast.error('Unable to update shipping regions');
    } finally {
      setIsLoadingRegions(false);
    }
  };

  const handleCountryToggle = (countryId: string) => {
    setSelectedCountryIds((prev) => {
      const isCurrentlySelected = prev.includes(countryId);
      
      if (isCurrentlySelected) {
        // Deselect country and all its states
        const statesToRemove = allStates
          .filter((s) => s.countryId === countryId)
          .map((s) => s.id);
        setSelectedStateIds((prevStates) => 
          prevStates.filter((id) => !statesToRemove.includes(id))
        );
        return prev.filter((id) => id !== countryId);
      } else {
        // Select country and all its states
        const statesToAdd = allStates
          .filter((s) => s.countryId === countryId && s.isActive)
          .map((s) => s.id);
        setSelectedStateIds((prevStates) => {
          const newStateIds = [...prevStates];
          statesToAdd.forEach((stateId) => {
            if (!newStateIds.includes(stateId)) {
              newStateIds.push(stateId);
            }
          });
          return newStateIds;
        });
        return [...prev, countryId];
      }
    });
  };

  const handleStateToggle = (stateId: string) => {
    setSelectedStateIds((prev) => {
      if (prev.includes(stateId)) {
        return prev.filter((id) => id !== stateId);
      } else {
        return [...prev, stateId];
      }
    });
  };

  if (isLoading) {
    return (
      <div className="flex h-64 items-center justify-center text-gray-500">
        <Loader2 className="mr-2 h-5 w-5 animate-spin" />
        Loading shipping method…
      </div>
    );
  }

  if (!method) {
    return (
      <div className="space-y-6">
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 text-center">
          <h2 className="text-xl font-semibold text-gray-900 mb-2">{error ?? 'Shipping Method Not Found'}</h2>
          <Link
            href="/admin/shipping-methods"
            className="inline-block bg-gray-900 text-white px-6 py-2 rounded-lg hover:bg-gray-800 transition-colors mt-4"
          >
            Back to Shipping Methods
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Link href="/admin/shipping-methods" className="p-2 hover:bg-gray-100 rounded-lg transition-colors">
          <ArrowLeft className="w-5 h-5" />
        </Link>
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Edit Shipping Method</h1>
          <p className="text-gray-600 mt-1">Manage shipping method and its rules</p>
        </div>
      </div>

      {error && (
        <div className="rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>
      )}

      {/* Method Details */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h2 className="text-xl font-semibold text-gray-900 mb-6">Method Details</h2>
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Method Name *</label>
            <input
              type="text"
              value={methodFormData.name}
              onChange={(e) => setMethodFormData((prev) => ({ ...prev, name: e.target.value }))}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Description</label>
            <textarea
              value={methodFormData.description}
              onChange={(e) => setMethodFormData((prev) => ({ ...prev, description: e.target.value }))}
              rows={3}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
            />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Display Order</label>
              <input
                type="number"
                value={methodFormData.order}
                onChange={(e) => setMethodFormData((prev) => ({ ...prev, order: e.target.value }))}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
              />
            </div>
            <div className="flex items-center pt-8">
              <input
                type="checkbox"
                id="methodIsActive"
                checked={methodFormData.isActive}
                onChange={(e) => setMethodFormData((prev) => ({ ...prev, isActive: e.target.checked }))}
                className="w-4 h-4 text-gray-900 border-gray-300 rounded focus:ring-gray-900"
              />
              <label htmlFor="methodIsActive" className="ml-2 text-sm text-gray-700">
                Active
              </label>
            </div>
          </div>
          <div className="flex justify-end">
            <button
              onClick={handleSaveMethod}
              disabled={isSavingMethod}
              className="bg-gray-900 text-white px-6 py-2 rounded-lg hover:bg-gray-800 transition-colors disabled:opacity-70 disabled:cursor-not-allowed"
            >
              {isSavingMethod ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin inline mr-2" />
                  Saving...
                </>
              ) : (
                'Save Method'
              )}
            </button>
          </div>
        </div>
      </div>

      {/* Regions Section */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h2 className="text-xl font-semibold text-gray-900 mb-4">Shipping Regions</h2>
        <p className="text-sm text-gray-600 mb-6">
          Select countries or states where this shipping method applies. Leave empty to apply to all locations.
        </p>

        <div className="space-y-6">
          {/* Countries Selection */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">Countries</label>
            <div className="border border-gray-300 rounded-lg p-4 max-h-48 overflow-y-auto">
              {countries.length === 0 ? (
                <p className="text-sm text-gray-500">No countries available</p>
              ) : (
                <div className="space-y-2">
                  {countries.map((country) => (
                    <label
                      key={country.id}
                      className="flex items-center space-x-2 cursor-pointer hover:bg-gray-50 p-2 rounded"
                    >
                      <input
                        type="checkbox"
                        checked={selectedCountryIds.includes(country.id)}
                        onChange={() => handleCountryToggle(country.id)}
                        className="w-4 h-4 text-gray-900 border-gray-300 rounded focus:ring-gray-900"
                      />
                      <span className="text-sm text-gray-700">{country.name} ({country.code})</span>
                    </label>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* States Selection */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">States/Provinces</label>
            <div className="border border-gray-300 rounded-lg p-4 max-h-64 overflow-y-auto">
              {allStates.length === 0 ? (
                <p className="text-sm text-gray-500">No states available</p>
              ) : (
                <div className="space-y-2">
                  {allStates.map((state) => (
                    <label
                      key={state.id}
                      className="flex items-center space-x-2 cursor-pointer hover:bg-gray-50 p-2 rounded"
                    >
                      <input
                        type="checkbox"
                        checked={selectedStateIds.includes(state.id)}
                        onChange={() => handleStateToggle(state.id)}
                        className="w-4 h-4 text-gray-900 border-gray-300 rounded focus:ring-gray-900"
                      />
                      <span className="text-sm text-gray-700">
                        {state.name}
                        {state.country && ` (${state.country.name})`}
                      </span>
                    </label>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* Selected Regions Summary */}
          {(selectedCountryIds.length > 0 || selectedStateIds.length > 0) && (
            <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
              <p className="text-sm font-medium text-gray-700 mb-2">Selected Regions:</p>
              <div className="flex flex-wrap gap-2">
                {selectedCountryIds.map((countryId) => {
                  const country = countries.find((c) => c.id === countryId);
                  return country ? (
                    <span
                      key={`country-${countryId}`}
                      className="inline-flex items-center gap-1 px-2 py-1 bg-blue-100 text-blue-800 rounded text-xs"
                    >
                      {country.name}
                      <button
                        onClick={() => handleCountryToggle(countryId)}
                        className="text-blue-600 hover:text-blue-800"
                      >
                        <X className="w-3 h-3" />
                      </button>
                    </span>
                  ) : null;
                })}
                {selectedStateIds.map((stateId) => {
                  const state = allStates.find((s) => s.id === stateId);
                  return state ? (
                    <span
                      key={`state-${stateId}`}
                      className="inline-flex items-center gap-1 px-2 py-1 bg-green-100 text-green-800 rounded text-xs"
                    >
                      {state.name}
                      {state.country && ` (${state.country.name})`}
                      <button
                        onClick={() => handleStateToggle(stateId)}
                        className="text-green-600 hover:text-green-800"
                      >
                        <X className="w-3 h-3" />
                      </button>
                    </span>
                  ) : null;
                })}
              </div>
            </div>
          )}

          {/* Save Button */}
          <div className="flex justify-end">
            <button
              onClick={handleSaveRegions}
              disabled={isLoadingRegions}
              className="bg-gray-900 text-white px-6 py-2 rounded-lg hover:bg-gray-800 transition-colors disabled:opacity-70 disabled:cursor-not-allowed"
            >
              {isLoadingRegions ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin inline mr-2" />
                  Saving Regions...
                </>
              ) : (
                'Save Regions'
              )}
            </button>
          </div>
        </div>
      </div>

      {/* Rules Section */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-xl font-semibold text-gray-900">Shipping Rules</h2>
          <button
            onClick={() => handleOpenRuleModal('create')}
            className="flex items-center gap-2 bg-gray-900 text-white px-4 py-2 rounded-lg hover:bg-gray-800 transition-colors"
          >
            <Plus className="w-5 h-5" />
            Add Rule
          </button>
        </div>

        {rules.length === 0 ? (
          <div className="text-center py-12 text-gray-500">
            <p className="mb-4">No shipping rules yet.</p>
            <button
              onClick={() => handleOpenRuleModal('create')}
              className="inline-flex items-center gap-2 bg-gray-900 text-white px-4 py-2 rounded-lg hover:bg-gray-800 transition-colors"
            >
              <Plus className="w-5 h-5" />
              Add First Rule
            </button>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50 border-b border-gray-200">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Weight Range</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Cost</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Priority</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {rules.map((rule) => (
                  <tr key={rule.id} className={rule.isActive ? '' : 'opacity-60'}>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm font-medium text-gray-900">{rule.name}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900">
                        {rule.minWeight} {rule.weightUnit}
                        {rule.maxWeight ? ` - ${rule.maxWeight} ${rule.weightUnit}` : '+'}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900">
                        {rule.currency} {rule.cost.toFixed(2)}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-500">{rule.priority}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <button
                        onClick={() => toggleRuleActive(rule)}
                        className={`px-3 py-1 rounded-full text-xs font-medium ${
                          rule.isActive
                            ? 'bg-green-100 text-green-800 hover:bg-green-200'
                            : 'bg-gray-100 text-gray-800 hover:bg-gray-200'
                        }`}
                      >
                        {rule.isActive ? 'Active' : 'Inactive'}
                      </button>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => handleOpenRuleModal('edit', rule)}
                          className="p-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded"
                        >
                          <Edit className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleDeleteRule(rule)}
                          className="p-2 text-red-600 hover:text-red-700 hover:bg-red-50 rounded"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Rule Modal */}
      {ruleModalMode && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full p-6 max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-2xl font-bold text-gray-900">
                {ruleModalMode === 'create' ? 'Add New Shipping Rule' : 'Edit Shipping Rule'}
              </h2>
              <button
                onClick={handleCloseRuleModal}
                className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Rule Name *</label>
                <input
                  type="text"
                  value={ruleFormData.name}
                  onChange={(e) => setRuleFormData((prev) => ({ ...prev, name: e.target.value }))}
                  placeholder="e.g., 0-5kg"
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Minimum Weight *</label>
                  <input
                    type="number"
                    value={ruleFormData.minWeight}
                    onChange={(e) => setRuleFormData((prev) => ({ ...prev, minWeight: e.target.value }))}
                    step="0.001"
                    min="0"
                    placeholder="0.000"
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Maximum Weight (leave empty for unlimited)</label>
                  <input
                    type="number"
                    value={ruleFormData.maxWeight}
                    onChange={(e) => setRuleFormData((prev) => ({ ...prev, maxWeight: e.target.value }))}
                    step="0.001"
                    min="0"
                    placeholder="Leave empty for unlimited"
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Weight Unit *</label>
                  <select
                    value={ruleFormData.weightUnit}
                    onChange={(e) => setRuleFormData((prev) => ({ ...prev, weightUnit: e.target.value }))}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                  >
                    {WEIGHT_UNITS.map((unit) => (
                      <option key={unit} value={unit}>
                        {unit}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Cost *</label>
                  <input
                    type="number"
                    value={ruleFormData.cost}
                    onChange={(e) => setRuleFormData((prev) => ({ ...prev, cost: e.target.value }))}
                    step="0.01"
                    min="0"
                    placeholder="0.00"
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Currency *</label>
                  <select
                    value={ruleFormData.currency}
                    onChange={(e) => setRuleFormData((prev) => ({ ...prev, currency: e.target.value }))}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                  >
                    {CURRENCIES.map((currency) => (
                      <option key={currency} value={currency}>
                        {currency}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Priority</label>
                  <input
                    type="number"
                    value={ruleFormData.priority}
                    onChange={(e) => setRuleFormData((prev) => ({ ...prev, priority: e.target.value }))}
                    placeholder="0"
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                  />
                  <p className="mt-1 text-xs text-gray-500">Higher priority rules are checked first</p>
                </div>
              </div>
              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="ruleIsActive"
                  checked={ruleFormData.isActive}
                  onChange={(e) => setRuleFormData((prev) => ({ ...prev, isActive: e.target.checked }))}
                  className="w-4 h-4 text-gray-900 border-gray-300 rounded focus:ring-gray-900"
                />
                <label htmlFor="ruleIsActive" className="ml-2 text-sm text-gray-700">
                  Active
                </label>
              </div>
            </div>
            <div className="flex gap-3 mt-6">
              <button
                onClick={handleSubmitRule}
                disabled={isSubmittingRule}
                className="flex-1 bg-gray-900 text-white px-4 py-2 rounded-lg hover:bg-gray-800 transition-colors disabled:opacity-70 disabled:cursor-not-allowed"
              >
                {isSubmittingRule ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin inline mr-2" />
                    Saving...
                  </>
                ) : ruleModalMode === 'create' ? (
                  'Add Rule'
                ) : (
                  'Update Rule'
                )}
              </button>
              <button
                onClick={handleCloseRuleModal}
                disabled={isSubmittingRule}
                className="flex-1 bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300 transition-colors disabled:opacity-70 disabled:cursor-not-allowed"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

