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-[var(--color-accent-500)]" />
        <span className="ml-2 text-[var(--text-secondary)]">Loading...</span>
      </div>
    );
  }

  // Render error state
  if (error) {
    return (
      <div className="p-4 bg-[var(--error-bg)] border border-[var(--error-border)] rounded-[var(--radius-card)]">
        <div className="flex items-center">
          <svg className="h-5 w-5 text-[var(--error-text)]" 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-[var(--error-text)]">{error}</span>
        </div>
        <button
          onClick={() => id && fetchData(id)}
          className="mt-2 text-sm text-[var(--error-text)] hover:opacity-80 underline"
        >
          Try again
        </button>
      </div>
    );
  }

  return (
    <div className="bg-[var(--bg-card)] rounded-[var(--radius-card)] shadow-sm border border-[var(--border-color)]">
      {/* Header */}
      <div className="px-6 py-4 border-b border-[var(--border-color)]">
        <h2 className="text-xl font-semibold text-[var(--text-primary)]">
          {id ? 'Edit' : 'Create'} {{name}}
        </h2>
        {isDirty && (
          <span className="text-sm text-[var(--warning-text)]">Unsaved changes</span>
        )}
      </div>

      {/* Form */}
      <form onSubmit={handleSubmit} className="p-6 space-y-6">
        {/* TODO: Add form fields */}
        <div className="text-[var(--text-secondary)] 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-[var(--border-color)]">
            {onCancel && (
              <button
                type="button"
                onClick={handleCancel}
                disabled={isLoading}
                className="px-4 py-2 text-[var(--text-secondary)] bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-[var(--radius-button)] hover:bg-[var(--bg-hover)] disabled:opacity-50"
              >
                Cancel
              </button>
            )}
            <button
              type="submit"
              disabled={isLoading || !isDirty}
              className="px-4 py-2 text-white bg-[var(--color-accent-600)] rounded-[var(--radius-button)] hover:bg-[var(--color-accent-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,
  };
}
