import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Play, MoreHorizontal, Loader2 } from "lucide-react";
import { useState, useEffect } from "react";
import { CallDetailsModal } from "./CallDetailsModal";
import { API_URL } from "@/lib/config";
import { useTranslation } from "react-i18next";

interface CallLog {
  time: string;
  customer: string;
  intent: string;
  outcome: string;
  duration: string;
  sentiment: string;
  cost: string;
  outcomeColor: string;
  sentimentColor: string;
}

const getSentimentEmoji = (sentiment: string) => {
  switch (sentiment) {
    case "Positive":
      return "😊";
    case "Negative":
      return "😠";
    case "Neutral":
      return "😐";
    default:
      return "😐";
  }
};

export function RecentCallsTable() {
  const { t } = useTranslation();
  const [recentCalls, setRecentCalls] = useState<CallLog[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedCall, setSelectedCall] = useState(null);
  const [isModalOpen, setIsModalOpen] = useState(false);

  useEffect(() => {
    const fetchRecentCalls = async () => {
      try {
        const sessionData = localStorage.getItem('session_data');
        if (!sessionData) {
          throw new Error('No session data found');
        }

        const session = JSON.parse(sessionData);
        const response = await fetch(`${API_URL}/api/call-logs`, {
          headers: {
            'Authorization': `Bearer ${session.session.access_token}`,
            'Content-Type': 'application/json'
          }
        });

        if (!response.ok) {
          throw new Error('Failed to fetch call logs');
        }

        const data = await response.json();
        if (data.success && data.call_logs) {
          // Take only the 5 most recent calls
          setRecentCalls(data.call_logs.slice(0, 5));
        }
      } catch (err) {
        console.error('Error fetching call logs:', err);
        setError(err instanceof Error ? err.message : 'Failed to load call logs');
      } finally {
        setLoading(false);
      }
    };

    fetchRecentCalls();
  }, []);

  const handleDetailsClick = (call) => {
    setSelectedCall(call);
    setIsModalOpen(true);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setSelectedCall(null);
  };

  return (
    <>
      <Card className="bg-slate-800 border-slate-700">
        <div className="p-6">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-semibold text-white">{t('dashboard.recentCalls.title')}</h3>
            <span className="text-sm text-slate-400">{t('dashboard.recentCalls.timeframe')}</span>
          </div>

          {loading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="w-8 h-8 text-slate-400 animate-spin" />
            </div>
          ) : error ? (
            <div className="text-center text-slate-400 py-12">
              {error}
            </div>
          ) : recentCalls.length === 0 ? (
            <div className="text-center text-slate-400 py-12">
              {t('dashboard.recentCalls.noCalls')}
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-slate-700">
                    <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('dashboard.recentCalls.headers.time')}</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('dashboard.recentCalls.headers.customer')}</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('dashboard.recentCalls.headers.intent')}</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('dashboard.recentCalls.headers.outcome')}</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('dashboard.recentCalls.headers.duration')}</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('dashboard.recentCalls.headers.sentiment')}</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('dashboard.recentCalls.headers.cost')}</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('dashboard.recentCalls.headers.actions')}</th>
                  </tr>
                </thead>
                <tbody>
                  {recentCalls.map((call, index) => (
                    <tr key={index} className="border-b border-slate-700/50 hover:bg-slate-700/30">
                      <td className="py-3 px-4 text-sm text-slate-300">{call.time}</td>
                      <td className="py-3 px-4 text-sm text-white">{call.customer}</td>
                      <td className="py-3 px-4 text-sm text-slate-300">{call.intent}</td>
                      <td className="py-3 px-4">
                        <span className={`text-sm font-medium ${call.outcomeColor}`}>
                          {call.outcome}
                        </span>
                      </td>
                      <td className="py-3 px-4 text-sm text-slate-300">{call.duration}</td>
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-2">
                          <span className="text-sm">{getSentimentEmoji(call.sentiment)}</span>
                          <span className={`text-sm ${call.sentimentColor}`}>
                            {call.sentiment}
                          </span>
                        </div>
                      </td>
                      <td className="py-3 px-4 text-sm text-slate-300">{call.cost}</td>
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-2">
                          <Button variant="ghost" size="sm" className="text-slate-400 hover:text-white">
                            <Play className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="text-slate-400 hover:text-white"
                            onClick={() => handleDetailsClick(call)}
                          >
                            <MoreHorizontal className="w-4 h-4" />
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </Card>

      {selectedCall && (
        <CallDetailsModal
          isOpen={isModalOpen}
          onClose={handleCloseModal}
          call={selectedCall}
        />
      )}
    </>
  );
}
