import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/common/ui/card";
import { ChevronDown } from "lucide-react";
import { cn } from "@/super-admin/lib/utils";

interface ReportStats {
  assigned: number;
  approved: number;
  pending: number;
  rejected: number;
  reassigned: number;
  replied: number;
}

interface DepartmentData extends ReportStats {
  [key: string]: any;
}

interface IncomingReportAccordionProps {
  data: Record<string, DepartmentData>;
  title?: string;
}

const StatBadge: React.FC<{ label: string; value: number; color: string }> = ({
  label,
  value,
  color,
}) => (
  <div className="flex items-center gap-2">
    <span className={cn("text-xs font-medium px-2 py-1 rounded-md", color)}>
      {label}: {value}
    </span>
  </div>
);

const DepartmentRow: React.FC<{
  name: string;
  stats: ReportStats;
  isExpanded: boolean;
  onToggle: () => void;
  hasChildren: boolean;
  level: number;
}> = ({ name, stats, isExpanded, onToggle, hasChildren, level }) => {
  const paddingLeft = level * 20;

  return (
    <div className="border-b border-gray-200 dark:border-gray-700">
      <button
        onClick={onToggle}
        className={cn(
          "w-full px-4 py-3 flex items-center justify-between hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",
          level > 0 && "bg-gray-50 dark:bg-gray-900"
        )}
        style={{ paddingLeft: `${paddingLeft + 16}px` }}
      >
        <div className="flex items-center gap-3 flex-1">
          {hasChildren && (
            <ChevronDown
              className={cn(
                "h-4 w-4 text-gray-600 dark:text-gray-400 transition-transform",
                isExpanded && "rotate-180"
              )}
            />
          )}
          {!hasChildren && <div className="w-4" />}
          <span className="font-medium text-gray-800 dark:text-gray-100 text-sm">
            {name}
          </span>
        </div>
      </button>

      {isExpanded && (
        <div className="bg-white dark:bg-gray-800 px-4 py-3 border-t border-gray-100 dark:border-gray-700">
          <div className="flex flex-wrap gap-2">
            <StatBadge
              label="Assigned"
              value={stats.assigned}
              color="bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200"
            />
            <StatBadge
              label="Approved"
              value={stats.approved}
              color="bg-primary-100 dark:bg-primary-900 text-primary-800 dark:text-primary-200"
            />
            <StatBadge
              label="Pending"
              value={stats.pending}
              color="bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200"
            />
            <StatBadge
              label="Rejected"
              value={stats.rejected}
              color="bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200"
            />
            <StatBadge
              label="Reassigned"
              value={stats.reassigned}
              color="bg-purple-100 dark:bg-purple-900 text-purple-800 dark:text-purple-200"
            />
            <StatBadge
              label="Replied"
              value={stats.replied}
              color="bg-indigo-100 dark:bg-indigo-900 text-indigo-800 dark:text-indigo-200"
            />
          </div>
        </div>
      )}
    </div>
  );
};

const NestedDepartment: React.FC<{
  name: string;
  data: DepartmentData;
  level: number;
}> = ({ name, data, level }) => {
  const [expandedItems, setExpandedItems] = useState<Record<string, boolean>>({});

  const stats: ReportStats = {
    assigned: data.assigned,
    approved: data.approved,
    pending: data.pending,
    rejected: data.rejected,
    reassigned: data.reassigned,
    replied: data.replied,
  };

  const children = Object.entries(data).filter(
    ([key]) =>
      ![
        "assigned",
        "approved",
        "pending",
        "rejected",
        "reassigned",
        "replied",
      ].includes(key)
  );

  const hasChildren = children.length > 0;

  const toggleExpand = (key: string) => {
    setExpandedItems((prev) => ({
      ...prev,
      [key]: !prev[key],
    }));
  };

  return (
    <>
      <DepartmentRow
        name={name}
        stats={stats}
        isExpanded={expandedItems[name] || false}
        onToggle={() => toggleExpand(name)}
        hasChildren={hasChildren}
        level={level}
      />
      {expandedItems[name] &&
        hasChildren &&
        children.map(([childName, childData]) => (
          <NestedDepartment
            key={childName}
            name={childName}
            data={childData as DepartmentData}
            level={level + 1}
          />
        ))}
    </>
  );
};

export const IncomingReportAccordion: React.FC<IncomingReportAccordionProps> = ({
  data,
  title = "Incoming Report",
}) => {
  const [expandedDepts, setExpandedDepts] = useState<Record<string, boolean>>({});

  const toggleDepartment = (deptName: string) => {
    setExpandedDepts((prev) => ({
      ...prev,
      [deptName]: !prev[deptName],
    }));
  };

  return (
    <Card className="shadow-md border border-gray-200 dark:border-gray-700 rounded-xl bg-white dark:bg-gray-800">
      <CardHeader className="border-b border-gray-200 dark:border-gray-700">
        <CardTitle className="text-lg font-semibold text-gray-800 dark:text-gray-100">
          {title}
        </CardTitle>
      </CardHeader>
      <CardContent className="p-0">
        <div className="divide-y divide-gray-200 dark:divide-gray-700">
          {Object.entries(data).map(([deptName, deptData]) => (
            <NestedDepartment
              key={deptName}
              name={deptName}
              data={deptData as DepartmentData}
              level={0}
            />
          ))}
        </div>
      </CardContent>
    </Card>
  );
};
