import { useState, useEffect } from 'react';
import type { GridColDef } from '@mui/x-data-grid';
import { SchemaService } from '../services/api';

const mapSqlTypeToMuiType = (sqlType: string): 'string' | 'number' | 'date' | 'dateTime' | 'boolean' => {
  sqlType = sqlType.toLowerCase();
  if (sqlType.includes('int') || sqlType.includes('decimal') || sqlType.includes('float') || sqlType.includes('double')) return 'number';
  if (sqlType.includes('datetime') || sqlType.includes('timestamp')) return 'dateTime';
  if (sqlType.includes('date')) return 'date';
  if (sqlType.includes('bool') || sqlType.includes('tinyint(1)')) return 'boolean';
  return 'string';
};

export const useTableSchema = (activeTable: string | null, activeDatabase: string | null) => {
  const [columns, setColumns] = useState<GridColDef[]>([]);
  const [loading, setLoading] = useState(false);
  const [primaryKey, setPrimaryKey] = useState<string>('id');

  useEffect(() => {
    const fetchSchema = async () => {
      if (!activeTable || !activeDatabase) return;
      
      setLoading(true);
      try {
        const schemaRes = await SchemaService.getTableSchema(activeTable, activeDatabase);
        let pk = 'id';
        const cols: GridColDef[] = schemaRes.data.map((col: any) => {
          if (col.Key === 'PRI') pk = col.Field;
          const type = mapSqlTypeToMuiType(col.Type);
          return {
            field: col.Field,
            headerName: col.Field,
            type: type,
            width: 200,
            minWidth: 100,
            editable: col.Key !== 'PRI', // Enable editing if not primary key
            valueGetter: (value: any) => {
              if ((type === 'date' || type === 'dateTime') && value && typeof value === 'string') {
                return new Date(value);
              }
              return value;
            },
          };
        });
        setColumns(cols);
        setPrimaryKey(pk);
      } catch (error) {
        console.error('Failed to fetch table schema', error);
      } finally {
        setLoading(false);
      }
    };

    fetchSchema();
  }, [activeTable, activeDatabase]);

  return { columns, loading, primaryKey };
};
