import React, { useEffect, useState } from "react";
import { Card, Tag, Button } from "antd";
import {
  UserOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined,
  ArrowRightOutlined,
} from "@ant-design/icons";
import { useNavigate } from "react-router-dom";

interface TodayAttendanceProps {
  data?: {
    date: string;
    totalEmployees: number;
    present: number;
    absent: number;
    halfDay: number;
    attendanceRate: number;
  } | null;
  loading?: boolean;
}

/* ───── Animated Donut Gauge ───── */
const DonutGauge: React.FC<{ percent: number; color: string; size?: number }> = ({ percent, color, size = 160 }) => {
  const [animatedPercent, setAnimatedPercent] = useState(0);

  useEffect(() => {
    // Small delay so the animation is visible on mount
    const timeout = setTimeout(() => setAnimatedPercent(percent), 100);
    return () => clearTimeout(timeout);
  }, [percent]);

  const strokeWidth = 12;
  const radius = (size - strokeWidth) / 2;
  const circumference = 2 * Math.PI * radius;
  const offset = circumference - (animatedPercent / 100) * circumference;

  const uniqueId = `donut-gradient-${color.replace("#", "")}`;

  return (
    <div style={{ position: "relative", width: size, height: size }}>
      <svg width={size} height={size} style={{ transform: "rotate(-90deg)" }}>
        <defs>
          <linearGradient id={uniqueId} x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor={color} stopOpacity={1} />
            <stop offset="100%" stopColor={color} stopOpacity={0.5} />
          </linearGradient>
          <filter id="donut-shadow">
            <feDropShadow dx="0" dy="1" stdDeviation="2" floodColor={color} floodOpacity="0.3" />
          </filter>
        </defs>

        {/* Trail */}
        <circle
          cx={size / 2}
          cy={size / 2}
          r={radius}
          fill="none"
          stroke="#e2e8f0"
          strokeWidth={strokeWidth}
        />

        {/* Filled arc */}
        <circle
          cx={size / 2}
          cy={size / 2}
          r={radius}
          fill="none"
          stroke={`url(#${uniqueId})`}
          strokeWidth={strokeWidth}
          strokeLinecap="round"
          strokeDasharray={circumference}
          strokeDashoffset={offset}
          filter="url(#donut-shadow)"
          style={{
            transition: "stroke-dashoffset 1.2s cubic-bezier(0.4, 0, 0.2, 1)",
          }}
        />
      </svg>

      {/* Center text */}
      <div
        style={{
          position: "absolute",
          inset: 0,
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <span
          style={{
            fontSize: 32,
            fontWeight: 800,
            color,
            lineHeight: 1,
            fontFamily: "'Inter', sans-serif",
          }}
        >
          {animatedPercent}
          <span style={{ fontSize: 14, fontWeight: 600 }}>%</span>
        </span>
        <span style={{ fontSize: 10, color: "#94a3b8", fontWeight: 500, marginTop: 2 }}>
          Rate
        </span>
      </div>
    </div>
  );
};

/* ───── Attendance Card ───── */
export const AttendanceCard: React.FC<TodayAttendanceProps> = ({ data, loading }) => {
  const navigate = useNavigate();

  const total = data?.totalEmployees ?? 0;
  const present = data?.present ?? 0;
  const absent = data?.absent ?? 0;
  const halfDay = data?.halfDay ?? 0;
  const rate = data?.attendanceRate ?? (total > 0 ? Math.round(((present + halfDay * 0.5) / total) * 100) : 0);

  const getProgressColor = (percent: number) => {
    if (percent >= 85) return "#10b981"; // Emerald green
    if (percent >= 70) return "#3b82f6"; // Blue
    if (percent >= 50) return "#f59e0b"; // Amber
    return "#ef4444"; // Red
  };

  const color = getProgressColor(rate);

  const getLabel = (percent: number) => {
    if (percent >= 85) return "Excellent";
    if (percent >= 70) return "Good";
    if (percent >= 50) return "Average";
    return "Low";
  };

  return (
    <Card
      loading={loading}
      style={{
        borderRadius: 20,
        boxShadow: "0 10px 30px rgba(0,0,0,0.04)",
        border: "1px solid #e2e8f0",
        background: "linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",
        height: "100%",
      }}
      styles={{ body: { padding: "20px 24px" } }}
    >
      {/* Header */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ fontSize: 20 }}>📋</span>
            <h3 style={{ margin: 0, fontSize: 17, fontWeight: 700, color: "#1e293b" }}>
              Today's Attendance
            </h3>
          </div>
          <p style={{ margin: "2px 0 0 28px", fontSize: 12, color: "#64748b" }}>
            Real-time presence summary
          </p>
        </div>
        <Button
          type="primary"
          ghost
          size="small"
          icon={<ArrowRightOutlined />}
          onClick={() => navigate("/attendance")}
          style={{
            borderRadius: 12,
            fontWeight: 600,
            fontSize: 12,
            height: 32,
            borderColor: "#3b82f6",
            color: "#2563eb",
          }}
        >
          Open Module
        </Button>
      </div>

      {/* Summary Grid Cards */}
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          gap: 10,
          marginBottom: 18,
        }}
      >
        {/* Total */}
        <div
          style={{
            background: "#eff6ff",
            border: "1px solid #dbeafe",
            borderRadius: 14,
            padding: "10px 8px",
            textAlign: "center",
          }}
        >
          <div style={{ fontSize: 11, color: "#3b82f6", fontWeight: 600, marginBottom: 2 }}>
            <UserOutlined /> Total
          </div>
          <div style={{ fontSize: 22, fontWeight: 800, color: "#1d4ed8" }}>{total}</div>
        </div>

        {/* Present */}
        <div
          style={{
            background: "#ecfdf5",
            border: "1px solid #a7f3d0",
            borderRadius: 14,
            padding: "10px 8px",
            textAlign: "center",
          }}
        >
          <div style={{ fontSize: 11, color: "#059669", fontWeight: 600, marginBottom: 2 }}>
            <CheckCircleOutlined /> Present
          </div>
          <div style={{ fontSize: 22, fontWeight: 800, color: "#047857" }}>{present}</div>
        </div>

        {/* Absent */}
        <div
          style={{
            background: "#fef2f2",
            border: "1px solid #fecaca",
            borderRadius: 14,
            padding: "10px 8px",
            textAlign: "center",
          }}
        >
          <div style={{ fontSize: 11, color: "#dc2626", fontWeight: 600, marginBottom: 2 }}>
            <CloseCircleOutlined /> Absent
          </div>
          <div style={{ fontSize: 22, fontWeight: 800, color: "#b91c1c" }}>{absent}</div>
        </div>

        {/* Half Day */}
        <div
          style={{
            background: "#fffbeb",
            border: "1px solid #fde68a",
            borderRadius: 14,
            padding: "10px 8px",
            textAlign: "center",
          }}
        >
          <div style={{ fontSize: 11, color: "#d97706", fontWeight: 600, marginBottom: 2 }}>
            <ClockCircleOutlined /> Half Day
          </div>
          <div style={{ fontSize: 22, fontWeight: 800, color: "#b45309" }}>{halfDay}</div>
        </div>
      </div>

      {/* Animated Donut Gauge Section */}
      <div
        style={{
          // background: "#fff",
          borderRadius: 14,
          padding: "20px 16px",
          // border: "1px solid #f1f5f9",
          // boxShadow: "inset 0 1px 3px rgba(0,0,0,0.02)",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          gap: 14,
        }}
      >
        <DonutGauge percent={rate} color={color} />

        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
          <Tag
            style={{
              borderRadius: 10,
              fontWeight: 700,
              fontSize: 12,
              background: color,
              color: "#fff",
              border: "none",
              paddingInline: 12,
            }}
          >
            {getLabel(rate)}
          </Tag>
          <div style={{ fontSize: 12, color: "#94a3b8", lineHeight: 1.6, textAlign: "center" }}>
            <span style={{ color: "#10b981", fontWeight: 600 }}>{present}</span> present
            {absent > 0 && (
              <>
                {" · "}
                <span style={{ color: "#ef4444", fontWeight: 600 }}>{absent}</span> absent
              </>
            )}
            {halfDay > 0 && (
              <>
                {" · "}
                <span style={{ color: "#f59e0b", fontWeight: 600 }}>{halfDay}</span> half day
              </>
            )}
          </div>
        </div>
      </div>
    </Card>
  );
};

export default AttendanceCard;
