import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { ChevronRight, Loader2 } from "lucide-react";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { API_URL } from "@/lib/config";
import { supabase } from "@/lib/supabase";
import { useTranslation } from "react-i18next";

interface CallLog {
  id: string;
  store_id: string;
  created_at: string;
  started_at: string | null;
  ended_at: string | null;
  duration: number | null;
  caller: string | null;
}

const formatDuration = (seconds: number | null): string => {
  if (!seconds) return "-";
  const mins = Math.floor(seconds / 60);
  const secs = Math.round(seconds % 60);
  return `${mins}:${secs.toString().padStart(2, '0')}`;
};

const formatDateTime = (dateStr: string | null): string => {
  if (!dateStr) return "-";
  const date = new Date(dateStr);
  return date.toLocaleString();
};

const maskPhoneNumber = (phone: string | null): string => {
  if (!phone) return "-";
  if (phone.length <= 4) return phone;
  const last4 = phone.slice(-4);
  return `***${last4}`;
};

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

  useEffect(() => {
    const fetchRecentCalls = async () => {
      try {
        const { data: { session } } = await supabase.auth.getSession();
        if (!session) {
          throw new Error('Not authenticated');
        }

        const response = await fetch(`${API_URL}/api/call-logs`, {
          headers: {
            'Authorization': `Bearer ${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 handleRowClick = (callId: string) => {
    navigate(`/call-logs/${callId}`);
  };

  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>
          <Button
            variant="ghost"
            size="sm"
            className="text-cyan-400 hover:text-cyan-300"
            onClick={() => navigate('/call-logs')}
          >
            {t('dashboard.recentCalls.viewAll')}
            <ChevronRight className="w-4 h-4 ml-1" />
          </Button>
        </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.caller')}</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-right py-3 px-4 text-sm font-medium text-slate-400"></th>
                </tr>
              </thead>
              <tbody>
                {recentCalls.map((call) => (
                  <tr
                    key={call.id}
                    className="border-b border-slate-700/50 hover:bg-slate-700/30 cursor-pointer transition-colors"
                    onClick={() => handleRowClick(call.id)}
                  >
                    <td className="py-3 px-4 text-sm text-slate-300">{formatDateTime(call.started_at)}</td>
                    <td className="py-3 px-4 text-sm text-white">{maskPhoneNumber(call.caller)}</td>
                    <td className="py-3 px-4 text-sm text-slate-300">{formatDuration(call.duration)}</td>
                    <td className="py-3 px-4 text-right">
                      <ChevronRight className="w-4 h-4 text-slate-400 inline-block" />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </Card>
  );
}
