import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Plus, Trash2, MessageSquare, Workflow as WorkflowIcon } from 'lucide-react';
import apiClient from '../../api/client';
import type { Workflow } from '../../types';
import { useChatStore } from '../../store/useChatStore';

interface LeftPanelProps {
  activeTab: string;
}

export function LeftPanel({ activeTab }: LeftPanelProps) {
  const { t } = useTranslation();
  const [workflows, setWorkflows] = useState<Workflow[]>([]);
  const [loadingWorkflows, setLoadingWorkflows] = useState(false);

  const {
    sessions,
    activeSessionId,
    setActiveSessionId,
    removeSession,
    createChat,
    selectedWorkflow,
    setSelectedWorkflow,
  } = useChatStore();

  useEffect(() => {
    let intervalId: ReturnType<typeof setInterval>;

    const fetchWorkflows = async (isInitial = false) => {
      if (isInitial) setLoadingWorkflows(true);
      try {
        const response = await apiClient.get('/api/v1/workflow/list');
        const data = response.data;
        let parsedWorkflows: Workflow[] = [];
        if (Array.isArray(data)) {
          parsedWorkflows = data;
        } else if (data && typeof data === 'object') {
          parsedWorkflows = data.workflows || Object.values(data);
        }
        setWorkflows(parsedWorkflows);
      } catch (error) {
        console.error('Failed to fetch workflows', error);
        setWorkflows([]);
      } finally {
        if (isInitial) setLoadingWorkflows(false);
      }
    };

    if (activeTab === 'workflows') {
      fetchWorkflows(true);
      intervalId = setInterval(() => fetchWorkflows(false), 2000);
    }

    return () => {
      if (intervalId) clearInterval(intervalId);
    };
  }, [activeTab]);

  const handleNewChat = async () => {
    await createChat(t('chat.newChat'), '你好');
  };

  const handleDeleteChat = (e: React.MouseEvent, id: string) => {
    e.stopPropagation();
    removeSession(id);
  };

  const isChats = activeTab === 'chats';

  return (
    <div className="w-[260px] bg-bg-sidebar border-r border-border-primary flex flex-col shrink-0">
      <div className="flex items-center justify-between px-4 py-4">
        <span className="text-[11px] font-semibold text-text-muted uppercase tracking-[1.5px]">
          {isChats ? t('chat.chatHistory') : t('nav.workflow')}
        </span>
        <button
          onClick={() => {
            if (isChats) handleNewChat();
            else setSelectedWorkflow('new');
          }}
          className="w-[26px] h-[26px] rounded-md bg-bg-card text-text-secondary hover:bg-accent hover:text-white transition-all flex items-center justify-center shadow-[0_1px_2px_rgba(0,0,0,0.04)]"
          title={isChats ? t('chat.newChat') : t('workflow.createWorkflow')}
        >
          <Plus size={12} />
        </button>
      </div>

      <div className="flex-1 overflow-y-auto px-2 pb-2">
        {isChats ? (
          sessions.length === 0 ? (
            <div className="px-3 py-8 text-center text-text-muted text-xs">
              {t('chat.noHistory')}
            </div>
          ) : (
            sessions.map((session) => {
              const isActive = activeSessionId === session.id;
              return (
                <div
                  key={session.id}
                  onClick={() => setActiveSessionId(session.id)}
                  className={`group flex items-center gap-2.5 px-2.5 py-2 rounded-lg cursor-pointer transition-all mb-px ${
                    isActive
                      ? 'bg-bg-card shadow-[0_1px_3px_rgba(0,0,0,0.04)]'
                      : 'hover:bg-white/60 dark:hover:bg-white/[0.04]'
                  }`}
                >
                  <div className={`w-7 h-7 rounded-[7px] flex items-center justify-center flex-shrink-0 ${isActive ? 'bg-accent-light' : 'bg-bg-primary'}`}>
                    <MessageSquare size={12} className={isActive ? 'text-accent' : 'text-text-muted'} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <h3 className={`text-xs truncate ${isActive ? 'text-text-primary font-medium' : 'text-text-secondary'}`}>
                      {session.title}
                    </h3>
                  </div>
                  <button
                    onClick={(e) => handleDeleteChat(e, session.id)}
                    className="opacity-0 group-hover:opacity-100 p-1 rounded text-text-muted hover:text-danger transition-all"
                  >
                    <Trash2 size={11} />
                  </button>
                </div>
              );
            })
          )
        ) : (
          loadingWorkflows ? (
            <div className="px-3 py-8 text-center text-text-muted text-xs">{t('workflow.loading')}</div>
          ) : workflows.length === 0 ? (
            <div className="px-3 py-8 text-center text-text-muted text-xs">
              {t('workflow.noWorkflows')}
            </div>
          ) : (
            workflows.map((wf) => {
              const isActive = selectedWorkflow === wf.trace_id;
              return (
                <div
                  key={wf.trace_id}
                  onClick={() => setSelectedWorkflow(wf.trace_id)}
                  className={`group flex items-center gap-2.5 px-2.5 py-2 rounded-lg cursor-pointer transition-all mb-px ${
                    isActive
                      ? 'bg-bg-card shadow-[0_1px_3px_rgba(0,0,0,0.04)]'
                      : 'hover:bg-white/60 dark:hover:bg-white/[0.04]'
                  }`}
                >
                  <div className={`w-7 h-7 rounded-[7px] flex items-center justify-center flex-shrink-0 ${isActive ? 'bg-accent-light' : 'bg-bg-primary'}`}>
                    <WorkflowIcon size={12} className={isActive ? 'text-accent' : 'text-text-muted'} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <h3 className={`text-xs truncate ${isActive ? 'text-text-primary font-medium' : 'text-text-secondary'}`}>
                      {wf.title || t('common.unnamed')}
                    </h3>
                  </div>
                </div>
              );
            })
          )
        )}
      </div>
    </div>
  );
}
