import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card } from "@/components/ui/card";
import { Search, Download, Calendar, Filter, Play, MoreHorizontal } from "lucide-react";
import { useState, useEffect } from "react";
import { CallDetailsModal } from "./CallDetailsModal";
import { ExportModal, ExportFormat } from "./ExportModal";
import { exportCallLogs } from "@/lib/exportUtils";
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 maskPhoneNumber = (phone: string | undefined ) => {
  if (!phone) return "";
  const last4 = phone.slice(-4);
  return `...xxx-${last4}`;
};

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

export function CallLogsContent() {
  const { t } = useTranslation();
  const [selectedCall, setSelectedCall] = useState<CallLog | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isExportModalOpen, setIsExportModalOpen] = useState(false);
  const [callLogs, setCallLogs] = useState<CallLog[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchCallLogs = async () => {
    setIsLoading(true);
    setError(null);
    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        throw new Error('No session data found');
      }

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

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

      const data = await response.json();
      setCallLogs(data.call_logs);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchCallLogs();
  }, []);

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

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

  const handleExportClick = () => {
    setIsExportModalOpen(true);
  };

  const handleCloseExportModal = () => {
    setIsExportModalOpen(false);
  };

  const handleExport = (format: ExportFormat) => {
    const timestamp = new Date().toISOString().split('T')[0];
    const filename = `call-logs-${timestamp}`;
    exportCallLogs(callLogs, format, filename);
  };

  return (
    <>
      <div className="flex-1 bg-slate-900 text-white">
        {/* Header */}
        <div className="border-b border-slate-800 bg-slate-900">
          <div className="flex items-center justify-between p-6">
            <div>
              <h1 className="text-2xl font-semibold text-white">{t('callLogs.title')}</h1>
              <p className="text-slate-400">{t('callLogs.subtitle')}</p>
            </div>

            <div className="flex items-center gap-4">
              <Button
                className="bg-slate-700 hover:bg-slate-600 text-white"
                onClick={handleExportClick}
                disabled={isLoading || callLogs.length === 0}
              >
                <Download className="w-4 h-4 mr-2" />
                {t('callLogs.export')}
              </Button>

              <Button className="bg-slate-700 hover:bg-slate-600 text-white">
                <Calendar className="w-4 h-4 mr-2" />
                {t('callLogs.dateRange')}
              </Button>
            </div>
          </div>
        </div>

        {/* Search and Filters */}
        <div className="p-6 border-b border-slate-800">
          <div className="flex items-center gap-4">
            <div className="relative flex-1 max-w-lg">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-4 h-4" />
              <Input
                placeholder={t('callLogs.searchPlaceholder')}
                className="pl-10 bg-slate-800 border-slate-700 text-white placeholder-slate-400"
              />
            </div>

            <Button variant="outline" className="border-slate-700 text-slate-300 hover:text-white hover:bg-slate-700">
              <Filter className="w-4 h-4 mr-2" />
              {t('callLogs.filters')}
            </Button>
          </div>
        </div>

        {/* Call Logs Table */}
        <div className="p-6">
          <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('callLogs.allCallLogs')}</h3>
                {!isLoading && !error && (
                  <Button
                    variant="ghost"
                    size="sm"
                    className="text-slate-400 hover:text-white"
                    onClick={fetchCallLogs}
                  >
                    <svg className="w-4 h-4 mr-2" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <path d="M23 4v6h-6M1 20v-6h6" strokeLinecap="round" strokeLinejoin="round"/>
                      <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                    {t('common.refresh')}
                  </Button>
                )}
              </div>

              {isLoading ? (
                <div className="flex flex-col items-center justify-center py-12">
                  <div className="relative">
                    <div className="w-12 h-12 border-4 border-slate-700 rounded-full"></div>
                    <div className="w-12 h-12 border-4 border-white border-t-transparent rounded-full animate-spin absolute top-0"></div>
                  </div>
                  <p className="text-slate-400 mt-4 font-medium">{t('callLogs.loadingCallLogs')}</p>
                </div>
              ) : error ? (
                <div className="flex flex-col items-center justify-center py-12">
                  <div className="w-16 h-16 bg-red-500/10 rounded-full flex items-center justify-center mb-4">
                    <svg className="w-8 h-8 text-red-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <circle cx="12" cy="12" r="10"/>
                      <line x1="12" y1="8" x2="12" y2="12"/>
                      <line x1="12" y1="16" x2="12.01" y2="16"/>
                    </svg>
                  </div>
                  <p className="text-red-500 font-medium mb-2">{t('callLogs.failedToLoad')}</p>
                  <p className="text-slate-400 text-sm mb-4">{error}</p>
                  <Button
                    className="bg-slate-700 hover:bg-slate-600 text-white"
                    onClick={fetchCallLogs}
                  >
                    <svg className="w-4 h-4 mr-2" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <path d="M23 4v6h-6M1 20v-6h6" strokeLinecap="round" strokeLinejoin="round"/>
                      <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                    {t('common.tryAgain')}
                  </Button>
                </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('callLogs.table.time')}</th>
                        <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('callLogs.table.customer')}</th>
                        <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('callLogs.table.intent')}</th>
                        <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('callLogs.table.outcome')}</th>
                        <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('callLogs.table.duration')}</th>
                        <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('callLogs.table.sentiment')}</th>
                        <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('callLogs.table.cost')}</th>
                        <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('callLogs.table.actions')}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {callLogs.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">{maskPhoneNumber(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>
        </div>
      </div>

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

      <ExportModal
        isOpen={isExportModalOpen}
        onClose={handleCloseExportModal}
        data={callLogs}
        onExport={handleExport}
      />
    </>
  );
}
