import React, { useEffect, useState } from 'react';
import { X } from 'lucide-react';
import { countriesApi } from '../../services/api';
 
interface Country {
  id: number;
  name: string;
  code?: string | null;
  is_active: number | boolean;
  created_at: string;
  updated_at: string;
}
 
interface CountryDialogProps {
  country: Country | null;
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  mode: 'add' | 'edit' | 'view';
}
 
const CountryDialog: React.FC<CountryDialogProps> = ({
  country,
  isOpen,
  onClose,
  onSuccess,
  mode,
}) => {
  const [formData, setFormData] = useState<{ name: string; code?: string; is_active: boolean }>({
    name: '',
    code: '',
    is_active: true,
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
 
  useEffect(() => {
    if (!isOpen) return;
    if (mode === 'add') {
      setFormData({ name: '', code: '', is_active: true });
      setError(null);
    } else if (country) {
      setFormData({
        name: country.name || '',
        code: country.code || '',
        is_active: !!country.is_active,
      });
      setError(null);
    }
  }, [isOpen, mode, country]);
 
  if (!isOpen) return null;
 
  const isEditable = mode === 'add' || mode === 'edit';
  const title = mode === 'add' ? 'Add Country' : mode === 'edit' ? 'Edit Country' : 'View Country';
 
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!isEditable) return;
    setLoading(true);
    setError(null);
    if (!formData.name.trim()) {
      setError('Country name is required.');
      setLoading(false);
      return;
    }
    try {
      let resp;
      if (mode === 'add') {
        resp = await countriesApi.createCountry({ name: formData.name.trim(), code: formData.code?.trim() || undefined });
      } else {
        if (!country) throw new Error('Country not selected');
        resp = await countriesApi.updateCountry(country.id, { name: formData.name.trim(), code: formData.code?.trim() || undefined, is_active: formData.is_active });
      }
      if (resp.status === 'success') {
        onSuccess();
        onClose();
      } else {
        throw new Error(resp.message || 'Operation failed');
      }
    } catch (err: any) {
      setError(err.message || 'Failed to save country');
    } finally {
      setLoading(false);
    }
  };
 
  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg p-6 w-full max-w-md mx-4 shadow-xl">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold text-gray-900">{title}</h3>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600">
            <X className="h-5 w-5" />
          </button>
        </div>
        {error && (
          <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
            {error}
          </div>
        )}
        <form onSubmit={handleSubmit}>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Country Name *</label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => setFormData((p) => ({ ...p, name: e.target.value }))}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
                disabled={!isEditable || loading}
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Country Code</label>
              <input
                type="text"
                value={formData.code || ''}
                onChange={(e) => setFormData((p) => ({ ...p, code: e.target.value }))}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
                disabled={!isEditable || loading}
              />
            </div>
            <div className="flex items-center">
              <input
                type="checkbox"
                checked={formData.is_active}
                onChange={(e) => setFormData((p) => ({ ...p, is_active: e.target.checked }))}
                className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded disabled:opacity-50"
                disabled={!isEditable || loading}
              />
              <span className="ml-2 text-sm text-gray-700">Is Active</span>
            </div>
          </div>
          {isEditable && (
            <div className="flex justify-end space-x-3 mt-6">
              <button
                type="button"
                onClick={onClose}
                className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                disabled={loading}
              >
                Cancel
              </button>
              <button
                type="submit"
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                disabled={loading}
              >
                {mode === 'add' ? 'Create Country' : 'Update Country'}
              </button>
            </div>
          )}
        </form>
      </div>
    </div>
  );
};
 
export default CountryDialog;
