// components/AircallDashboard.jsx
import React, { useState, useEffect } from "react";
import { Card, CardContent } from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";

// Import shared components and tokens
import {
  DashboardChartTooltip,
  DashboardStatCard,
  DashboardStatCardSkeleton,
  DashboardSectionHeader,
  DashboardErrorState,
  DashboardTable,
  ChartSkeleton,
  CARD_STYLES,
  METRIC_COLORS,
} from "@/components/dashboard/shared";
import { Phone, Clock, Zap, Timer } from "lucide-react";

// Aircall-specific colors using the standardized palette
const CHART_COLORS = {
  inbound: METRIC_COLORS.aov,        // Purple for inbound
  outbound: METRIC_COLORS.revenue,   // Green for outbound
  missed: METRIC_COLORS.comparison,  // Amber for missed
  answered: METRIC_COLORS.revenue,   // Green for answered
  duration: METRIC_COLORS.orders,    // Blue for duration
  hourly: METRIC_COLORS.tertiary,    // Pink for hourly
};

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 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 safeArray = (arr) => (Array.isArray(arr) ? arr : []);

  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 chartData = {
    hourly: metrics?.by_hour
      ? metrics.by_hour.map((count, hour) => ({
          hour: new Date(2000, 0, 1, hour).toLocaleString('en-US', {
            hour: 'numeric',
            hour12: true
          }).toUpperCase(),
          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: new Date(day.date).toLocaleString('en-US', {
        month: 'short',
        day: 'numeric'
      }),
    })),
  };

  // Column definitions for Agent Performance table
  const agentColumns = [
    {
      key: "name",
      header: "Agent",
      render: (value) => <span className="font-medium text-foreground">{value}</span>,
    },
    {
      key: "total",
      header: "Total Calls",
      align: "right",
      sortable: true,
      render: (value) => <span className="text-muted-foreground">{value}</span>,
    },
    {
      key: "answered",
      header: "Answered",
      align: "right",
      sortable: true,
      render: (value) => <span className="text-trend-positive">{value}</span>,
    },
    {
      key: "missed",
      header: "Missed",
      align: "right",
      sortable: true,
      render: (value) => <span className="text-trend-negative">{value}</span>,
    },
    {
      key: "average_duration",
      header: "Avg Duration",
      align: "right",
      sortable: true,
      render: (value) => <span className="text-muted-foreground">{formatDuration(value)}</span>,
    },
  ];

  // Column definitions for Missed Reasons table
  const missedReasonsColumns = [
    {
      key: "reason",
      header: "Reason",
      render: (value) => <span className="font-medium text-foreground">{value}</span>,
    },
    {
      key: "count",
      header: "Count",
      align: "right",
      render: (value) => <span className="text-trend-negative">{value}</span>,
    },
  ];

  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 (
      <Card className={CARD_STYLES.base}>
        <CardContent className="p-4">
          <DashboardErrorState
            title="Failed to load call data"
            message={error}
          />
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="space-y-6">
      <Card className={CARD_STYLES.base}>
        <DashboardSectionHeader
          title="Calls"
          timeSelector={
            <Select value={timeRange} onValueChange={setTimeRange}>
              <SelectTrigger className="w-[130px] h-9">
                <SelectValue placeholder="Select range" />
              </SelectTrigger>
              <SelectContent>
                {TIME_RANGES.map((range) => (
                  <SelectItem key={range.value} value={range.value}>
                    {range.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          }
        />

        <CardContent className="p-6 pt-0 space-y-4">
          {/* Metric Cards */}
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 dashboard-stagger">
            {isLoading ? (
              [...Array(4)].map((_, i) => (
                <DashboardStatCardSkeleton key={i} hasSubtitle />
              ))
            ) : metrics ? (
              <>
                <DashboardStatCard
                  title="Total Calls"
                  value={metrics.total}
                  subtitle={
                    <span className="flex gap-3">
                      <span><span className="text-chart-orders">↑ {metrics.by_direction.inbound}</span> in</span>
                      <span><span className="text-chart-revenue">↓ {metrics.by_direction.outbound}</span> out</span>
                    </span>
                  }
                  icon={Phone}
                  iconColor="blue"
                />

                <DashboardStatCard
                  title="Answer Rate"
                  value={`${((metrics.by_status.answered / metrics.total) * 100).toFixed(1)}%`}
                  subtitle={
                    <span className="flex gap-3">
                      <span><span className="text-trend-positive">{metrics.by_status.answered}</span> answered</span>
                      <span><span className="text-trend-negative">{metrics.by_status.missed}</span> missed</span>
                    </span>
                  }
                  icon={Zap}
                  iconColor="green"
                />

                <DashboardStatCard
                  title="Peak Hour"
                  value={
                    metrics?.by_hour
                      ? new Date(2000, 0, 1, metrics.by_hour.indexOf(Math.max(...metrics.by_hour)))
                          .toLocaleString('en-US', { hour: 'numeric', hour12: true }).toUpperCase()
                      : 'N/A'
                  }
                  subtitle={`Busiest Agent: ${sortedAgents[0]?.name || "N/A"}`}
                  icon={Clock}
                  iconColor="purple"
                />

                <DashboardStatCard
                  title="Avg Duration"
                  value={formatDuration(metrics.average_duration)}
                  subtitle={
                    metrics?.daily_data?.length > 0
                      ? `${Math.round(metrics.total / metrics.daily_data.length)} calls/day`
                      : "N/A"
                  }
                  tooltip={
                    metrics?.duration_distribution
                      ? `Duration Distribution: ${metrics.duration_distribution.map(d => `${d.range}: ${d.count}`).join(', ')}`
                      : undefined
                  }
                  icon={Timer}
                  iconColor="teal"
                />
              </>
            ) : null}
          </div>

          {/* Charts and Tables Section */}
          <div className="space-y-4">
            {/* Charts Row */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
              {/* Daily Call Volume */}
              <Card className={CARD_STYLES.base}>
                <DashboardSectionHeader title="Daily Call Volume" compact />
                <CardContent className="h-[300px]">
                  {isLoading ? (
                    <ChartSkeleton type="bar" height="md" withCard={false} />
                  ) : (
                    <ResponsiveContainer width="100%" height="100%">
                      <BarChart data={chartData.daily} margin={{ top: 0, right: 5, left: -35, bottom: 0 }}>
                        <CartesianGrid strokeDasharray="3 3" className="stroke-border/40" />
                        <XAxis
                          dataKey="date"
                          tick={{ fontSize: 12 }}
                          className="text-muted-foreground"
                          tickLine={false}
                          axisLine={false}
                        />
                        <YAxis
                          tick={{ fontSize: 12 }}
                          className="text-muted-foreground"
                          tickLine={false}
                          axisLine={false}
                        />
                        <RechartsTooltip content={<DashboardChartTooltip />} />
                        <Legend />
                        <Bar dataKey="inbound" fill={CHART_COLORS.inbound} name="Inbound" radius={[4, 4, 0, 0]} />
                        <Bar dataKey="outbound" fill={CHART_COLORS.outbound} name="Outbound" radius={[4, 4, 0, 0]} />
                      </BarChart>
                    </ResponsiveContainer>
                  )}
                </CardContent>
              </Card>

              {/* Hourly Distribution */}
              <Card className={CARD_STYLES.base}>
                <DashboardSectionHeader title="Hourly Distribution" compact />
                <CardContent className="h-[300px]">
                  {isLoading ? (
                    <ChartSkeleton type="bar" height="md" withCard={false} />
                  ) : (
                    <ResponsiveContainer width="100%" height="100%">
                      <BarChart data={chartData.hourly} margin={{ top: 0, right: 5, left: -35, bottom: 0 }}>
                        <CartesianGrid strokeDasharray="3 3" className="stroke-border/40" />
                        <XAxis
                          dataKey="hour"
                          tick={{ fontSize: 12 }}
                          interval={2}
                          className="text-muted-foreground"
                          tickLine={false}
                          axisLine={false}
                        />
                        <YAxis
                          tick={{ fontSize: 12 }}
                          className="text-muted-foreground"
                          tickLine={false}
                          axisLine={false}
                        />
                        <RechartsTooltip content={<DashboardChartTooltip />} />
                        <Bar dataKey="calls" fill={CHART_COLORS.hourly} name="Calls" radius={[4, 4, 0, 0]} />
                      </BarChart>
                    </ResponsiveContainer>
                  )}
                </CardContent>
              </Card>
            </div>

            {/* Tables Row */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
              {/* Agent Performance */}
              <Card className={CARD_STYLES.base}>
                <DashboardSectionHeader title="Agent Performance" compact />
                <CardContent>
                  <DashboardTable
                    columns={agentColumns}
                    data={sortedAgents}
                    loading={isLoading}
                    skeletonRows={5}
                    getRowKey={(agent) => agent.id}
                    sortConfig={agentSort}
                    onSort={(key, direction) => setAgentSort({ key, direction })}
                    maxHeight="md"
                    compact
                  />
                </CardContent>
              </Card>

              {/* Missed Call Reasons Table */}
              <Card className={CARD_STYLES.base}>
                <DashboardSectionHeader title="Missed Call Reasons" compact />
                <CardContent>
                  <DashboardTable
                    columns={missedReasonsColumns}
                    data={chartData.missedReasons}
                    loading={isLoading}
                    skeletonRows={5}
                    getRowKey={(reason, index) => `${reason.reason}-${index}`}
                    maxHeight="md"
                    compact
                  />
                </CardContent>
              </Card>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default AircallDashboard;
