import React from "react";
import { AlertCircle, CheckCircle2, Clock3, Users } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import { Badge } from "@/shared/common/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/common/ui/table";
import { useTranslation } from "react-i18next";
import { useCollaborationByRecordId } from "../hooks/useMyCollaborations";
import { useLocalizedName } from "@/shared/common/localizedName";

interface CollaborationDetailsProps {
  open: boolean;
  onClose: () => void;
  recordId: string;
}

const CollaborationDetails: React.FC<CollaborationDetailsProps> = ({
  open,
  onClose,
  recordId,
}) => {
  const { t } = useTranslation();
  const localizedName = useLocalizedName();
  const { data, isLoading, error } = useCollaborationByRecordId(recordId, {
    enabled: open && !!recordId,
  });
  const items = data?.items || [];

  const getCollaboratorLabel = (item: any) => {
    return (
      localizedName(item?.employeePosition?.employee?.name) ||
      localizedName(item?.employee?.name) ||
      localizedName(item?.employeePosition?.position?.name) ||
      item?.employeePositionId ||
      "__"
    );
  };

  const getStatusLabel = (status?: string) => {
    if (!status) return "__";
    return t(`statusBar.${status}`, status);
  };

  const getStatusVariant = (status?: string) => {
    switch (status) {
      case "signed":
        return "success";
      case "rejected":
      case "reject":
        return "danger";
      default:
        return "secondary";
    }
  };

  const signedCount = items.filter((item: any) => item.signStatus === "signed").length;
  const pendingCount = items.filter(
    (item: any) => item.signStatus === "draft" || !item.signStatus,
  ).length;

  return (
    <Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
      <DialogContent className="overflow-hidden border-0 p-0 sm:max-w-[760px]">
        <DialogHeader className="border-b bg-gradient-to-r from-primary-600 via-primary-600 to-cyan-600 px-6 py-5 text-white">
          <div className="flex items-center gap-3">
            <div className="flex h-11 w-11 items-center justify-center rounded-2xl bg-white/15 backdrop-blur">
              <Users className="h-5 w-5" />
            </div>
            <div className="min-w-0">
              <DialogTitle className="text-xl font-semibold text-white">
                {t("header.navigation.collaboration")}
              </DialogTitle>
              <p className="mt-1 text-sm text-white/80">
                {t("viewDetail.collaborators", "Collaborator")} {items.length}
              </p>
            </div>
          </div>
        </DialogHeader>

        <div className="space-y-5 bg-slate-50 px-6 py-5">
          {!isLoading && !error && items.length > 0 && (
            <div className="grid gap-3 sm:grid-cols-3">
              <div className="rounded-2xl border border-primary-100 bg-white p-4 shadow-sm">
                <div className="flex items-center gap-3">
                  <div className="rounded-xl bg-primary-100 p-2 text-primary-700">
                    <Users className="h-4 w-4" />
                  </div>
                  <div>
                    <p className="text-xs font-medium uppercase tracking-wide text-slate-500">
                      {t("viewDetail.collaborators", "Collaborators")}
                    </p>
                    <p className="text-xl font-semibold text-slate-900">{items.length}</p>
                  </div>
                </div>
              </div>
              <div className="rounded-2xl border border-primary-100 bg-white p-4 shadow-sm">
                <div className="flex items-center gap-3">
                  <div className="rounded-xl bg-primary-100 p-2 text-primary-700">
                    <CheckCircle2 className="h-4 w-4" />
                  </div>
                  <div>
                    <p className="text-xs font-medium uppercase tracking-wide text-slate-500">
                      {t("statusBar.Accepted", "Signed")}
                    </p>
                    <p className="text-xl font-semibold text-slate-900">{signedCount}</p>
                  </div>
                </div>
              </div>
              <div className="rounded-2xl border border-amber-100 bg-white p-4 shadow-sm">
                <div className="flex items-center gap-3">
                  <div className="rounded-xl bg-amber-100 p-2 text-amber-700">
                    <Clock3 className="h-4 w-4" />
                  </div>
                  <div>
                    <p className="text-xs font-medium uppercase tracking-wide text-slate-500">
                      {t("statusBar.InProgress", "Pending")}
                    </p>
                    <p className="text-xl font-semibold text-slate-900">{pendingCount}</p>
                  </div>
                </div>
              </div>
            </div>
          )}

          {isLoading ? (
            <div className="rounded-2xl border border-slate-200 bg-white p-10 text-center shadow-sm">
              <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-slate-100">
                <Clock3 className="h-5 w-5 text-slate-500" />
              </div>
              <div className="text-sm font-medium text-slate-700">
                {t("setting.loading")}
              </div>
            </div>
          ) : error ? (
            <div className="rounded-2xl border border-red-100 bg-white p-10 text-center shadow-sm">
              <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-red-100">
                <AlertCircle className="h-5 w-5 text-red-600" />
              </div>
              <div className="text-sm font-medium text-red-600">
                {error instanceof Error
                  ? error.message
                  : t("msg.error", "Failed to load collaborations")}
              </div>
            </div>
          ) : !items?.length ? (
            <div className="rounded-2xl border border-slate-200 bg-white p-10 text-center shadow-sm">
              <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-slate-100">
                <Users className="h-5 w-5 text-slate-500" />
              </div>
              <div className="text-sm font-medium text-slate-700">{t("msg.noMsg")}</div>
            </div>
          ) : (
            <div className="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
              <div className="border-b bg-slate-50 px-4 py-3">
                <p className="text-sm font-semibold text-slate-800">
                  {t("header.navigation.collaboration")}
                </p>
              </div>
              <div className="max-h-[50vh] overflow-auto">
                <Table>
                  <TableHeader className="sticky top-0 z-10 bg-white">
                    <TableRow className="border-slate-200 hover:bg-transparent">
                      <TableHead className="h-12 px-4 text-xs font-semibold uppercase tracking-wide text-slate-500">
                        {t("viewDetail.collaborators", "Collaborator")}
                      </TableHead>
                      <TableHead className="h-12 px-4 text-xs font-semibold uppercase tracking-wide text-slate-500">
                        {t("userRecord.signStatus", "Status")}
                      </TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {items.map((item: any, index: number) => (
                      <TableRow
                        key={item.id}
                        className="border-slate-100 hover:bg-primary-50/40"
                      >
                        <TableCell className="px-4 py-4">
                          <div className="flex items-center gap-3">
                            <div className="flex h-9 w-9 items-center justify-center rounded-full bg-gradient-to-br from-primary-500 to-primary-600 text-xs font-semibold text-white">
                              {index + 1}
                            </div>
                            <div>
                              <p className="font-medium text-slate-900">
                                {getCollaboratorLabel(item)}
                              </p>
                              <p className="text-xs text-slate-500">
                                {item.employeePositionId || "__"}
                              </p>
                            </div>
                          </div>
                        </TableCell>
                        <TableCell className="px-4 py-4">
                          <Badge variant={getStatusVariant(item.signStatus) as any}>
                            {getStatusLabel(item.signStatus)}
                          </Badge>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default CollaborationDetails;
