import { useState, useEffect } from 'react';
import { Loader2, AlertCircle } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from './ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './ui/table';
import { Badge } from './ui/badge';
import { workflowService } from '../services/workflows';
import { Trigger } from '../types/trigger';
import { Action } from '../types/action';

interface DataFieldsModalProps {
  nodeType: 'trigger' | 'action';
  typeIdentifier: string | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

// Helper function to get badge color based on field type
function getTypeBadgeColor(type: string): string {
  switch (type) {
    case 'string':
      return 'bg-blue-100 text-blue-800 border-blue-200';
    case 'integer':
      return 'bg-green-100 text-green-800 border-green-200';
    case 'boolean':
      return 'bg-purple-100 text-purple-800 border-purple-200';
    case 'datetime':
      return 'bg-orange-100 text-orange-800 border-orange-200';
    case 'array':
      return 'bg-gray-100 text-gray-800 border-gray-200';
    default:
      return 'bg-gray-100 text-gray-800 border-gray-200';
  }
}

// Unified field type for display
interface DisplayField {
  name: string;
  type: string;
  description: string;
  example: string;
}

export function DataFieldsModal({
  nodeType,
  typeIdentifier,
  open,
  onOpenChange,
}: DataFieldsModalProps) {
  const [trigger, setTrigger] = useState<Trigger | null>(null);
  const [action, setAction] = useState<Action | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Fetch data when modal opens
  useEffect(() => {
    if (open && typeIdentifier) {
      if (nodeType === 'trigger') {
        fetchTriggerData();
      } else {
        fetchActionData();
      }
    }
  }, [open, typeIdentifier, nodeType]);

  const fetchTriggerData = async () => {
    if (!typeIdentifier) return;

    setIsLoading(true);
    setError(null);
    setAction(null);
    try {
      const triggers = await workflowService.getTriggers();
      const currentTrigger = triggers.find((t: Trigger) => t.type === typeIdentifier);
      setTrigger(currentTrigger || null);
    } catch (err) {
      setError('Failed to load trigger information. Please try again.');
      console.error('Error fetching triggers:', err);
    } finally {
      setIsLoading(false);
    }
  };

  const fetchActionData = async () => {
    if (!typeIdentifier) return;

    setIsLoading(true);
    setError(null);
    setTrigger(null);
    try {
      const actions = await workflowService.getActions();
      const currentAction = actions.find((a: Action) => a.type === typeIdentifier);
      setAction(currentAction || null);
    } catch (err) {
      setError('Failed to load action information. Please try again.');
      console.error('Error fetching actions:', err);
    } finally {
      setIsLoading(false);
    }
  };

  // Get fields based on node type
  const getFields = (): DisplayField[] => {
    if (nodeType === 'trigger' && trigger?.available_fields) {
      return [...trigger.available_fields].sort((a, b) => a.name.localeCompare(b.name));
    }
    if (nodeType === 'action' && action?.output_fields) {
      return [...action.output_fields].sort((a, b) => a.name.localeCompare(b.name));
    }
    return [];
  };

  const sortedFields = getFields();
  const currentItem = nodeType === 'trigger' ? trigger : action;
  const title = nodeType === 'trigger' ? 'Available Data Fields' : 'Output Fields';
  const emptyMessage =
    nodeType === 'trigger'
      ? 'No data fields available for this trigger.'
      : 'No output fields defined for this action.';
  const notFoundMessage =
    nodeType === 'trigger' ? 'Trigger information not found.' : 'Action information not found.';

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          {currentItem && (
            <DialogDescription asChild>
              <div className="space-y-1">
                <p className="text-sm text-slate-500">{currentItem.label}</p>
                <code className="block text-xs bg-slate-50 px-2 py-1 rounded font-mono text-slate-500 w-fit">
                  {currentItem.type}
                </code>
              </div>
            </DialogDescription>
          )}
        </DialogHeader>

        {/* Loading state */}
        {isLoading && (
          <div className="flex items-center gap-2 text-sm text-slate-500 py-8 justify-center">
            <Loader2 className="h-4 w-4 animate-spin" />
            <span>Loading {nodeType} information...</span>
          </div>
        )}

        {/* Error state */}
        {!isLoading && error && (
          <div className="flex items-center gap-2 text-sm text-red-600 py-4">
            <AlertCircle className="h-4 w-4" />
            <span>{error}</span>
          </div>
        )}

        {/* Content */}
        {!isLoading && !error && currentItem && (
          <>
            {sortedFields.length === 0 ? (
              <p className="text-sm text-slate-500 py-4">{emptyMessage}</p>
            ) : (
              <div className="border border-slate-200 rounded">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-slate-50">
                      <TableHead className="text-slate-900">Field Name</TableHead>
                      <TableHead className="text-slate-900">Type</TableHead>
                      <TableHead className="text-slate-900">Description</TableHead>
                      <TableHead className="text-slate-900">Example</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {sortedFields.map((field: DisplayField) => (
                      <TableRow key={field.name}>
                        <TableCell className="font-mono text-xs text-slate-900">
                          {field.name}
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline" className={getTypeBadgeColor(field.type)}>
                            {field.type}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-sm text-slate-500">
                          {field.description}
                        </TableCell>
                        <TableCell className="text-xs italic text-gray-500 font-mono">
                          {field.example}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </>
        )}

        {/* Not found */}
        {!isLoading && !error && !currentItem && typeIdentifier && (
          <p className="text-sm text-slate-500 py-4">{notFoundMessage}</p>
        )}
      </DialogContent>
    </Dialog>
  );
}
