/**
 * Carrier Form Component for Create/Edit
 */

import React, { useState } from 'react';
import { Eye, EyeOff } from 'lucide-react';
import { Carrier, CarrierStatus, CreateCarrierInput, UpdateCarrierInput } from '@/types/carrier';

interface CarrierFormProps {
  carrier?: Carrier;
  onSubmit: (data: CreateCarrierInput | UpdateCarrierInput) => Promise<void>;
  onCancel: () => void;
}

export const CarrierForm: React.FC<CarrierFormProps> = ({ carrier, onSubmit, onCancel }) => {
  const [formData, setFormData] = useState({
    name: carrier?.name || '',
    scac: carrier?.scac || '',
    status: carrier?.status || CarrierStatus.ACTIVE,
    apiEndpoint: carrier?.apiEndpoint || '',
    apiKey: carrier?.apiKey || '',
    priority: carrier?.priority?.toString() || '1',
    rateLimit: carrier?.rateLimit?.toString() || '100',
    timeout: carrier?.timeout?.toString() || '5000',
  });

  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showApiKey, setShowApiKey] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setError(null);

    try {
      await onSubmit({
        name: formData.name,
        scac: formData.scac,
        status: formData.status,
        apiEndpoint: formData.apiEndpoint || undefined,
        apiKey: formData.apiKey || undefined,
        priority: parseInt(formData.priority),
        rateLimit: parseInt(formData.rateLimit),
        timeout: parseInt(formData.timeout),
      });
    } catch (err: any) {
      setError(err.message || 'An error occurred');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {error && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-4">
          <p className="text-sm text-red-800">{error}</p>
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Name */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Carrier Name <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            required
            value={formData.name}
            onChange={e => setFormData({ ...formData, name: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        {/* SCAC */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            SCAC Code <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            required
            maxLength={4}
            value={formData.scac}
            onChange={e => setFormData({ ...formData, scac: e.target.value.toUpperCase() })}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        {/* Status */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Status</label>
          <select
            value={formData.status}
            onChange={e => setFormData({ ...formData, status: e.target.value as CarrierStatus })}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value={CarrierStatus.ACTIVE}>Active</option>
            <option value={CarrierStatus.INACTIVE}>Inactive</option>
            <option value={CarrierStatus.MAINTENANCE}>Maintenance</option>
          </select>
        </div>

        {/* Priority */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Priority</label>
          <input
            type="number"
            min="1"
            max="100"
            value={formData.priority}
            onChange={e => setFormData({ ...formData, priority: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        {/* API Endpoint */}
        <div className="md:col-span-2">
          <label className="block text-sm font-medium text-gray-700 mb-1">API Endpoint</label>
          <input
            type="url"
            value={formData.apiEndpoint}
            onChange={e => setFormData({ ...formData, apiEndpoint: e.target.value })}
            placeholder="https://api.carrier.com/v1"
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        {/* API Key */}
        <div className="md:col-span-2">
          <label className="block text-sm font-medium text-gray-700 mb-1">API Key</label>
          <div className="relative">
            <input
              type={showApiKey ? 'text' : 'password'}
              value={formData.apiKey}
              onChange={e => setFormData({ ...formData, apiKey: e.target.value })}
              placeholder="Enter API key"
              className="w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
            <button
              type="button"
              onClick={() => setShowApiKey(!showApiKey)}
              className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
              tabIndex={-1}
              aria-label={showApiKey ? 'Hide API key' : 'Show API key'}
            >
              {showApiKey ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
            </button>
          </div>
        </div>

        {/* Rate Limit */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Rate Limit (req/min)
          </label>
          <input
            type="number"
            min="1"
            value={formData.rateLimit}
            onChange={e => setFormData({ ...formData, rateLimit: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        {/* Timeout */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Timeout (ms)</label>
          <input
            type="number"
            min="1000"
            step="1000"
            value={formData.timeout}
            onChange={e => setFormData({ ...formData, timeout: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>
      </div>

      {/* Actions */}
      <div className="flex justify-end gap-3 pt-6 border-t border-gray-200">
        <button
          type="button"
          onClick={onCancel}
          disabled={submitting}
          className="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50"
        >
          Cancel
        </button>
        <button
          type="submit"
          disabled={submitting}
          className="px-4 py-2 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700 disabled:opacity-50"
        >
          {submitting ? 'Saving...' : carrier ? 'Update Carrier' : 'Create Carrier'}
        </button>
      </div>
    </form>
  );
};
