// components/AircallDashboard.jsx
import React, { useState, useEffect } from "react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  PhoneCall,
  PhoneMissed,
  Clock,
  UserCheck,
  PhoneIncoming,
  PhoneOutgoing,
  ArrowUpDown,
  Timer,
  Loader2,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  BarChart,
  Bar,
} from "recharts";
import { AgentStatsCard } from "@/components/dashboard/AgentStatsCard";
import { TableActions } from "@/components/dashboard/TableActions";

const COLORS = {
  inbound: "hsl(262.1 83.3% 57.8%)", // Purple
  outbound: "hsl(142.1 76.2% 36.3%)", // Green
  missed: "hsl(47.9 95.8% 53.1%)", // Yellow
  answered: "hsl(142.1 76.2% 36.3%)", // Green
  duration: "hsl(221.2 83.2% 53.3%)", // Blue
};

const TIME_RANGES = [
  { label: "Today", value: "today" },
  { label: "Yesterday", value: "yesterday" },
  { label: "Last 7 Days", value: "last7days" },
  { label: "Last 30 Days", value: "last30days" },
  { label: "Last 90 Days", value: "last90days" },
];

const REFRESH_INTERVAL = 5 * 60 * 1000;

const formatDuration = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = seconds % 60;

  if (hours > 0) {
    return `${hours}h ${minutes}m`;
  }
  return `${minutes}m ${remainingSeconds}s`;
};

const MetricCard = ({ title, value, subtitle, icon: Icon, iconColor }) => (
  <TooltipProvider>
    <Tooltip>
      <TooltipTrigger asChild>
        <Card className="bg-white dark:bg-gray-900/60 backdrop-blur-sm">
          <CardHeader className="flex flex-row items-center justify-between pb-2 p-4">
            <CardTitle className="text-sm font-medium text-gray-600 dark:text-gray-300">{title}</CardTitle>
            <Icon className={`h-4 w-4 ${iconColor}`} />
          </CardHeader>
          <CardContent className="p-4 pt-0">
            <div className="text-2xl font-bold text-gray-900 dark:text-gray-100">{value}</div>
            {subtitle && (
              <p className="text-sm text-muted-foreground mt-1">{subtitle}</p>
            )}
          </CardContent>
        </Card>
      </TooltipTrigger>
      <TooltipContent>
        <p>{title}</p>
      </TooltipContent>
    </Tooltip>
  </TooltipProvider>
);

const CustomTooltip = ({ active, payload, label }) => {
  if (active && payload && payload.length) {
    return (
      <Card className="p-3 shadow-lg bg-white dark:bg-gray-900/60 backdrop-blur-sm border-none">
        <CardContent className="p-0 space-y-2">
          <p className="font-medium text-sm text-gray-900 dark:text-gray-100 border-b border-gray-100 dark:border-gray-800 pb-1 mb-2">{label}</p>
          {payload.map((entry, index) => (
            <p key={index} className="text-sm text-muted-foreground">
              {`${entry.name}: ${entry.value}`}
            </p>
          ))}
        </CardContent>
      </Card>
    );
  }
  return null;
};

export const exportToCSV = (data, filename) => {
  const headers = [
    "Name",
    "Total Calls",
    "Answered",
    "Missed",
    "Answer Rate",
    "Avg Duration",
  ];
  const rows = data.map((agent) => [
    agent.name,
    agent.total,
    agent.answered,
    agent.missed,
    `${((agent.answered / agent.total) * 100).toFixed(1)}%`,
    formatDuration(agent.average_duration),
  ]);

  const csvContent = [
    headers.join(","),
    ...rows.map((row) => row.join(",")),
  ].join("\n");

  const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
  const link = document.createElement("a");
  const url = URL.createObjectURL(blob);
  link.setAttribute("href", url);
  link.setAttribute("download", `${filename}.csv`);
  link.style.visibility = "hidden";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const AgentPerformanceTable = ({ agents, onSort }) => {
  const [sortConfig, setSortConfig] = useState({
    key: "total",
    direction: "desc",
  });

  const handleSort = (key) => {
    const direction =
      sortConfig.key === key && sortConfig.direction === "desc"
        ? "asc"
        : "desc";
    setSortConfig({ key, direction });
    onSort(key, direction);
  };

  const SortButton = ({ column }) => (
    <Button
      variant="ghost"
      size="sm"
      onClick={() => handleSort(column)}
      className="flex items-center gap-1 hover:bg-transparent"
    >
      {column.charAt(0).toUpperCase() + column.slice(1)}
      <ArrowUpDown className="h-4 w-4" />
    </Button>
  );

  return (
    <Table>
      <TableHeader>
        <TableRow className="hover:bg-transparent">
          <TableHead>Agent</TableHead>
          <TableHead>
            <SortButton column="total" />
          </TableHead>
          <TableHead>
            <SortButton column="answered" />
          </TableHead>
          <TableHead>
            <SortButton column="missed" />
          </TableHead>
          <TableHead>
            <SortButton column="average_duration" />
          </TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {agents.map((agent) => (
          <TableRow key={agent.id} className="hover:bg-gray-50 dark:hover:bg-gray-800/50">
            <TableCell className="font-medium text-gray-900 dark:text-gray-100">{agent.name}</TableCell>
            <TableCell>{agent.total}</TableCell>
            <TableCell className="text-emerald-600 dark:text-emerald-400">{agent.answered}</TableCell>
            <TableCell className="text-rose-600 dark:text-rose-400">{agent.missed}</TableCell>
            <TableCell className="text-muted-foreground">{formatDuration(agent.average_duration)}</TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
};

const AircallDashboard = () => {
  const [timeRange, setTimeRange] = useState("last7days");
  const [metrics, setMetrics] = useState(null);
  const [lastUpdated, setLastUpdated] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [agentSort, setAgentSort] = useState({
    key: "total",
    direction: "desc",
  });
  const [searchTerm, setSearchTerm] = useState("");
  const [viewType, setViewType] = useState("table"); // 'table' or 'cards'

  const safeArray = (arr) => (Array.isArray(arr) ? arr : []);
  const safeObject = (obj) => (obj && typeof obj === "object" ? obj : {});

  const sortedAgents = metrics?.by_users
    ? Object.values(metrics.by_users).sort((a, b) => {
        const multiplier = agentSort.direction === "desc" ? -1 : 1;
        return multiplier * (a[agentSort.key] - b[agentSort.key]);
      })
    : [];

  const filteredAgents = sortedAgents.filter((agent) =>
    agent.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const formatDate = (dateString) => {
    try {
      // Parse the date string (YYYY-MM-DD)
      const [year, month, day] = dateString.split('-').map(Number);
      
      // Create a date object in ET timezone
      const date = new Date(Date.UTC(year, month - 1, day));
      
      // Format the date in ET timezone
      return new Intl.DateTimeFormat("en-US", {
        month: "short",
        day: "numeric",
        year: "numeric",
        timeZone: "America/New_York"
      }).format(date);
    } catch (error) {
      console.error("Date formatting error:", error, { dateString });
      return "Invalid Date";
    }
  };
  

  const handleExport = () => {
    const timestamp = new Intl.DateTimeFormat("en-US", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
    }).format(new Date());

    exportToCSV(filteredAgents, `aircall-agent-metrics-${timestamp}`);
  };

  const chartData = {
    hourly: metrics?.by_hour
      ? metrics.by_hour.map((count, hour) => ({
          hour: `${hour.toString().padStart(2, "0")}:00`,
          calls: count || 0,
        }))
      : [],

    missedReasons: metrics?.by_missed_reason
      ? Object.entries(metrics.by_missed_reason).map(([reason, count]) => ({
          reason: (reason || "").replace(/_/g, " "),
          count: count || 0,
        }))
      : [],

    daily: safeArray(metrics?.daily_data).map((day) => ({
      ...day,
      inbound: day.inbound || 0,
      outbound: day.outbound || 0,
      date: day.date || "",
    })),
  };

  const peakHour = metrics?.by_hour
    ? metrics.by_hour.indexOf(Math.max(...metrics.by_hour))
    : null;

  const busyAgent = sortedAgents?.length > 0 ? sortedAgents[0] : null;

  const bestAnswerRate = sortedAgents
    ?.filter((agent) => agent.total > 0)
    ?.sort((a, b) => b.answered / b.total - a.answered / a.total)[0];

  const fetchData = async () => {
    try {
      setIsLoading(true);
      const response = await fetch(`/api/aircall/metrics/${timeRange}`);
      if (!response.ok) throw new Error("Failed to fetch metrics");
      const data = await response.json();
      setMetrics(data);
      setLastUpdated(data._meta?.generatedAt);
      setError(null);
    } catch (err) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, REFRESH_INTERVAL);
    return () => clearInterval(interval);
  }, [timeRange]);

  if (error) {
    return (
      <Alert variant="destructive" className="m-4">
        <AlertDescription>Error loading call data: {error}</AlertDescription>
      </Alert>
    );
  }

  return (
    <div className="space-y-6">
      <Card className="bg-white dark:bg-gray-900/60 backdrop-blur-sm">
        <CardHeader className="p-6">
          <div className="flex justify-between items-center">
            <div>
              <CardTitle className="text-xl font-semibold text-gray-900 dark:text-gray-100">Aircall Analytics</CardTitle>
              {lastUpdated && (
                <CardDescription className="mt-1">
                  Last updated: {new Date(lastUpdated).toLocaleString()}
                </CardDescription>
              )}
            </div>

            <Select value={timeRange} onValueChange={setTimeRange}>
              <SelectTrigger className="w-[180px] h-9">
                <SelectValue placeholder="Select range" />
              </SelectTrigger>
              <SelectContent>
                {TIME_RANGES.map((range) => (
                  <SelectItem key={range.value} value={range.value}>
                    {range.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </CardHeader>

        <CardContent className="p-6 pt-0 space-y-6">
          {/* Metric Cards */}
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
            {isLoading ? (
              [...Array(6)].map((_, i) => (
                <Skeleton key={i} className="h-32 rounded-lg" />
              ))
            ) : metrics ? (
              <>
                <MetricCard
                  title="Total Calls"
                  value={metrics.total}
                  icon={PhoneCall}
                  iconColor="text-gray-500 dark:text-gray-400"
                />
                <MetricCard
                  title="Inbound"
                  value={metrics.by_direction.inbound}
                  subtitle={`${(
                    (metrics.by_direction.inbound / metrics.total) *
                    100
                  ).toFixed(1)}%`}
                  icon={PhoneIncoming}
                  iconColor="text-blue-500 dark:text-blue-400"
                />
                <MetricCard
                  title="Outbound"
                  value={metrics.by_direction.outbound}
                  subtitle={`${(
                    (metrics.by_direction.outbound / metrics.total) *
                    100
                  ).toFixed(1)}%`}
                  icon={PhoneOutgoing}
                  iconColor="text-emerald-500 dark:text-emerald-400"
                />
                <MetricCard
                  title="Missed"
                  value={metrics.by_status.missed}
                  subtitle={`${(
                    (metrics.by_status.missed / metrics.total) *
                    100
                  ).toFixed(1)}%`}
                  icon={PhoneMissed}
                  iconColor="text-rose-500 dark:text-rose-400"
                />
                <MetricCard
                  title="Avg Duration"
                  value={formatDuration(metrics.average_duration)}
                  icon={Clock}
                  iconColor="text-purple-500 dark:text-purple-400"
                />
                <MetricCard
                  title="Answer Rate"
                  value={`${(
                    (metrics.by_status.answered / metrics.total) *
                    100
                  ).toFixed(1)}%`}
                  icon={UserCheck}
                  iconColor="text-emerald-500 dark:text-emerald-400"
                />
              </>
            ) : null}
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Card className="bg-white dark:bg-gray-900/60 backdrop-blur-sm">
              <CardHeader>
                <CardTitle className="text-sm font-medium text-gray-900 dark:text-gray-100">Performance Summary</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2">
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">Peak Hour</span>
                  <span className="font-medium text-gray-900 dark:text-gray-100">
                    {metrics?.by_hour.indexOf(Math.max(...metrics.by_hour))}:00
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">Busiest Agent</span>
                  <span className="font-medium text-gray-900 dark:text-gray-100">
                    {sortedAgents[0]?.name || "N/A"}
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">Best Answer Rate</span>
                  <span className="font-medium text-gray-900 dark:text-gray-100">
                    {sortedAgents
                      .filter((agent) => agent.total > 0)
                      .sort(
                        (a, b) => b.answered / b.total - a.answered / a.total
                      )[0]?.name || "N/A"}
                  </span>
                </div>
              </CardContent>
            </Card>

            <Card className="bg-white dark:bg-gray-900/60 backdrop-blur-sm">
              <CardHeader>
                <CardTitle className="text-sm font-medium text-gray-900 dark:text-gray-100">Time Period</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2">
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">Date Range</span>
                  <span className="font-medium text-gray-900 dark:text-gray-100">
                    {metrics?.daily_data?.length > 0 ? (
                      <>
                        {formatDate(metrics.daily_data[0]?.date)} -{" "}
                        {formatDate(
                          metrics.daily_data[metrics.daily_data.length - 1]?.date
                        )}
                      </>
                    ) : (
                      "No data available"
                    )}
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">Avg Daily Calls</span>
                  <span className="font-medium text-gray-900 dark:text-gray-100">
                    {metrics?.daily_data?.length > 0
                      ? Math.round(metrics.total / metrics.daily_data.length)
                      : "N/A"}
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">Avg Duration</span>
                  <span className="font-medium text-gray-900 dark:text-gray-100">
                    {metrics?.average_duration
                      ? formatDuration(metrics.average_duration)
                      : "N/A"}
                  </span>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Charts */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* Daily Call Volume */}
            <Card className="bg-white dark:bg-gray-900/60 backdrop-blur-sm">
              <CardHeader>
                <CardTitle className="text-sm font-medium text-gray-900 dark:text-gray-100">Daily Call Volume</CardTitle>
              </CardHeader>
              <CardContent className="h-[300px]">
                <ResponsiveContainer width="100%" height="100%">
                  <LineChart data={chartData.daily}>
                    <CartesianGrid strokeDasharray="3 3" className="stroke-gray-200 dark:stroke-gray-700" />
                    <XAxis
                      dataKey="date"
                      tick={{ fontSize: 12 }}
                      className="text-gray-600 dark:text-gray-300"
                    />
                    <YAxis
                      tick={{ fontSize: 12 }}
                      className="text-gray-600 dark:text-gray-300"
                    />
                    <RechartsTooltip content={<CustomTooltip />} />
                    <Legend />
                    <Line
                      type="monotone"
                      dataKey="inbound"
                      stroke={COLORS.inbound}
                      name="Inbound"
                      strokeWidth={2}
                      dot={false}
                    />
                    <Line
                      type="monotone"
                      dataKey="outbound"
                      stroke={COLORS.outbound}
                      name="Outbound"
                      strokeWidth={2}
                      dot={false}
                    />
                  </LineChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            {/* Duration Distribution */}
            <Card className="bg-white dark:bg-gray-900/60 backdrop-blur-sm">
              <CardHeader>
                <CardTitle className="text-sm font-medium text-gray-900 dark:text-gray-100">Call Duration Distribution</CardTitle>
              </CardHeader>
              <CardContent className="h-[300px]">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={metrics?.duration_distribution || []}>
                    <CartesianGrid strokeDasharray="3 3" className="stroke-gray-200 dark:stroke-gray-700" />
                    <XAxis 
                      dataKey="range" 
                      className="text-gray-600 dark:text-gray-300"
                    />
                    <YAxis className="text-gray-600 dark:text-gray-300" />
                    <RechartsTooltip content={<CustomTooltip />} />
                    <Bar dataKey="count" fill={COLORS.duration} />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            {/* Missed Call Reasons */}
            <Card className="bg-white dark:bg-gray-900/60 backdrop-blur-sm">
              <CardHeader>
                <CardTitle className="text-sm font-medium text-gray-900 dark:text-gray-100">Missed Call Reasons</CardTitle>
              </CardHeader>
              <CardContent className="h-[300px]">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={chartData.missedReasons} layout="vertical">
                    <CartesianGrid strokeDasharray="3 3" className="stroke-gray-200 dark:stroke-gray-700" />
                    <XAxis type="number" className="text-gray-600 dark:text-gray-300" />
                    <YAxis
                      dataKey="reason"
                      type="category"
                      width={150}
                      className="text-gray-600 dark:text-gray-300"
                    />
                    <RechartsTooltip content={<CustomTooltip />} />
                    <Bar dataKey="count" fill={COLORS.missed} />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            {/* Hourly Distribution */}
            <Card className="bg-white dark:bg-gray-900/60 backdrop-blur-sm">
              <CardHeader>
                <CardTitle className="text-sm font-medium text-gray-900 dark:text-gray-100">Hourly Distribution</CardTitle>
              </CardHeader>
              <CardContent className="h-[300px]">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={chartData.hourly}>
                    <CartesianGrid strokeDasharray="3 3" className="stroke-gray-200 dark:stroke-gray-700" />
                    <XAxis
                      dataKey="hour"
                      tick={{ fontSize: 12 }}
                      interval={2}
                      className="text-gray-600 dark:text-gray-300"
                    />
                    <YAxis
                      tick={{ fontSize: 12 }}
                      className="text-gray-600 dark:text-gray-300"
                    />
                    <RechartsTooltip content={<CustomTooltip />} />
                    <Bar dataKey="calls" fill={COLORS.inbound} name="Calls" />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </div>

          {/* Agent Performance */}
          <Card className="bg-white dark:bg-gray-900/60 backdrop-blur-sm">
            <CardHeader>
              <div className="flex justify-between items-center">
                <CardTitle className="text-sm font-medium text-gray-900 dark:text-gray-100">Agent Performance</CardTitle>
                <div className="flex gap-2">
                  <Button
                    variant={viewType === "table" ? "default" : "outline"}
                    size="sm"
                    onClick={() => setViewType("table")}
                  >
                    Table
                  </Button>
                  <Button
                    variant={viewType === "cards" ? "default" : "outline"}
                    size="sm"
                    onClick={() => setViewType("cards")}
                  >
                    Cards
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <TableActions onSearch={setSearchTerm} onExport={handleExport} />

              {viewType === "table" ? (
                <AgentPerformanceTable
                  agents={filteredAgents}
                  onSort={(key, direction) => setAgentSort({ key, direction })}
                />
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {filteredAgents.map((agent) => (
                    <AgentStatsCard
                      key={agent.id}
                      agent={agent}
                      formatDuration={formatDuration}
                    />
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </CardContent>
      </Card>
    </div>
  );
};

export default AircallDashboard;
