import React, { useState, useEffect, useCallback } from 'react';

// ============================================================================
// Types
// ============================================================================

export interface {{name}}Data {
  id?: string;
  createdAt?: string;
  updatedAt?: string;
  // TODO: Add {{name}} specific properties
}

export interface {{name}}Props {
  /** Entity ID for edit mode */
  id?: string;
  /** Initial data */
  initialData?: Partial<{{name}}Data>;
  /** Callback when data is saved */
  onSave?: (data: {{name}}Data) => void;
  /** Callback when cancelled */
  onCancel?: () => void;
  /** Loading state from parent */
  loading?: boolean;
  /** Read-only mode */
  readOnly?: boolean;
}

// ============================================================================
// Component
// ============================================================================

/**
 * {{name}} component
 *
 * @example
 * ```tsx
 * <{{name}}
 *   id="123"
 *   onSave={(data) => console.log('Saved:', data)}
 *   onCancel={() => navigate(-1)}
 * />
 * ```
 */
export const {{name}}: React.FC<{{name}}Props> = ({
  id,
  initialData,
  onSave,
  onCancel,
  loading: externalLoading,
  readOnly = false,
}) => {
  // State
  const [data, setData] = useState<{{name}}Data>(initialData || {});
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isDirty, setIsDirty] = useState(false);

  // Combined loading state
  const isLoading = loading || externalLoading;

  // Fetch data when ID changes
  useEffect(() => {
    if (id && !initialData) {
      fetchData(id);
    }
  }, [id, initialData]);

  // Fetch data from API
  const fetchData = useCallback(async (fetchId: string) => {
    setLoading(true);
    setError(null);

    try {
      // TODO: Implement API call
      // const response = await {{nameCamel}}Api.getById(fetchId);
      // setData(response);

      // Placeholder
      setData({ id: fetchId });
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to load data');
    } finally {
      setLoading(false);
    }
  }, []);

  // Handle field change
  const handleChange = useCallback((field: keyof {{name}}Data, value: unknown) => {
    setData(prev => ({ ...prev, [field]: value }));
    setIsDirty(true);
  }, []);

  // Handle form submission
  const handleSubmit = useCallback(async (e: React.FormEvent) => {
    e.preventDefault();

    if (readOnly) return;

    setLoading(true);
    setError(null);

    try {
      // TODO: Implement API call
      // const result = data.id
      //   ? await {{nameCamel}}Api.update(data.id, data)
      //   : await {{nameCamel}}Api.create(data);

      if (onSave) {
        onSave(data);
      }

      setIsDirty(false);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to save');
    } finally {
      setLoading(false);
    }
  }, [data, onSave, readOnly]);

  // Handle cancel
  const handleCancel = useCallback(() => {
    if (isDirty) {
      const confirmed = window.confirm('You have unsaved changes. Are you sure you want to cancel?');
      if (!confirmed) return;
    }

    if (onCancel) {
      onCancel();
    }
  }, [isDirty, onCancel]);

  // Render loading state
  if (isLoading && !data.id) {
    return (
      <div className="flex items-center justify-center p-8">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500" />
        <span className="ml-2 text-gray-600">Loading...</span>
      </div>
    );
  }

  // Render error state
  if (error) {
    return (
      <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
        <div className="flex items-center">
          <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
            <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
          </svg>
          <span className="ml-2 text-red-700">{error}</span>
        </div>
        <button
          onClick={() => id && fetchData(id)}
          className="mt-2 text-sm text-red-600 hover:text-red-800 underline"
        >
          Try again
        </button>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-lg shadow-sm border border-gray-200">
      {/* Header */}
      <div className="px-6 py-4 border-b border-gray-200">
        <h2 className="text-xl font-semibold text-gray-900">
          {id ? 'Edit' : 'Create'} {{name}}
        </h2>
        {isDirty && (
          <span className="text-sm text-amber-600">Unsaved changes</span>
        )}
      </div>

      {/* Form */}
      <form onSubmit={handleSubmit} className="p-6 space-y-6">
        {/* TODO: Add form fields */}
        <div className="text-gray-500 text-center py-8">
          Add your form fields here
        </div>

        {/* Actions */}
        {!readOnly && (
          <div className="flex items-center justify-end gap-3 pt-4 border-t border-gray-200">
            {onCancel && (
              <button
                type="button"
                onClick={handleCancel}
                disabled={isLoading}
                className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50"
              >
                Cancel
              </button>
            )}
            <button
              type="submit"
              disabled={isLoading || !isDirty}
              className="px-4 py-2 text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isLoading ? 'Saving...' : 'Save'}
            </button>
          </div>
        )}
      </form>
    </div>
  );
};

export default {{name}};

// ============================================================================
// Hook
// ============================================================================

export interface Use{{name}}Options {
  id?: string;
  autoFetch?: boolean;
}

export function use{{name}}(options: Use{{name}}Options = {}) {
  const { id, autoFetch = true } = options;

  const [data, setData] = useState<{{name}}Data | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const fetch = useCallback(async (fetchId?: string) => {
    const targetId = fetchId || id;
    if (!targetId) return;

    setLoading(true);
    setError(null);

    try {
      // TODO: Implement API call
      // const result = await {{nameCamel}}Api.getById(targetId);
      // setData(result);
    } catch (e) {
      setError(e instanceof Error ? e : new Error('Unknown error'));
    } finally {
      setLoading(false);
    }
  }, [id]);

  const save = useCallback(async (saveData: {{name}}Data) => {
    setLoading(true);
    setError(null);

    try {
      // TODO: Implement API call
      // const result = saveData.id
      //   ? await {{nameCamel}}Api.update(saveData.id, saveData)
      //   : await {{nameCamel}}Api.create(saveData);
      // setData(result);
      // return result;
    } catch (e) {
      setError(e instanceof Error ? e : new Error('Unknown error'));
      throw e;
    } finally {
      setLoading(false);
    }
  }, []);

  const remove = useCallback(async (removeId?: string) => {
    const targetId = removeId || id;
    if (!targetId) return;

    setLoading(true);
    setError(null);

    try {
      // TODO: Implement API call
      // await {{nameCamel}}Api.delete(targetId);
      setData(null);
    } catch (e) {
      setError(e instanceof Error ? e : new Error('Unknown error'));
      throw e;
    } finally {
      setLoading(false);
    }
  }, [id]);

  useEffect(() => {
    if (autoFetch && id) {
      fetch();
    }
  }, [autoFetch, id, fetch]);

  return {
    data,
    loading,
    error,
    fetch,
    save,
    remove,
    setData,
  };
}
