import { Dialog } from "./Dialog.tsx";
import { Button } from "./Button.tsx";
import { AlertCircle, Play } from "lucide-react";
import { graphql, useLazyLoadQuery } from "react-relay";
import type { SyncSummaryModalQuery } from "../__generated__/SyncSummaryModalQuery.graphql.ts";

interface SyncSummaryModalProps {
  open: boolean;
  onClose: () => void;
  slice: string;
  collections: string[];
  externalCollections: string[];
  onConfirm: () => void;
  isConfirming?: boolean;
}

export function SyncSummaryModal({
  open,
  onClose,
  slice,
  collections,
  externalCollections,
  onConfirm,
  isConfirming = false,
}: SyncSummaryModalProps) {
  const data = useLazyLoadQuery<SyncSummaryModalQuery>(
    graphql`
      query SyncSummaryModalQuery($slice: String!, $collections: [String!], $externalCollections: [String!]) {
        getSyncSummary(slice: $slice, collections: $collections, externalCollections: $externalCollections) {
          totalRepos
          cappedRepos
          wouldBeCapped
          appliedLimit
          collectionsSummary {
            collection
            estimatedRepos
            isExternal
          }
        }
      }
    `,
    {
      slice,
      collections: collections.length > 0 ? collections : null,
      externalCollections: externalCollections.length > 0 ? externalCollections : null,
    },
    {
      fetchPolicy: 'network-only',
    }
  );

  const summary = data.getSyncSummary;

  if (!open || !summary) return null;

  return (
    <Dialog open={open} onClose={onClose} title="Sync Summary" maxWidth="2xl">
      <div className="space-y-6">
        {/* Repo Stats */}
        <div className={summary.wouldBeCapped ? "grid grid-cols-2 gap-4" : ""}>
          <div className="bg-zinc-800/50 rounded p-4">
            <div className="text-sm text-zinc-500 mb-1">Total Repos</div>
            <div className="text-2xl font-semibold text-zinc-200">
              {summary.totalRepos.toLocaleString()}
            </div>
          </div>
          {summary.wouldBeCapped && (
            <div className="bg-zinc-800/50 rounded p-4">
              <div className="text-sm text-zinc-500 mb-1">Will Sync</div>
              <div className="text-2xl font-semibold text-zinc-200">
                {summary.cappedRepos.toLocaleString()}
              </div>
            </div>
          )}
        </div>

        {/* Capped Warning */}
        {summary.wouldBeCapped && (
          <div className="flex items-start gap-3 p-4 bg-yellow-950/30 border border-yellow-900/50 rounded">
            <AlertCircle className="text-yellow-500 mt-0.5" size={20} />
            <div className="flex-1">
              <div className="text-sm font-medium text-yellow-400 mb-1">
                Sync Will Be Limited
              </div>
              <div className="text-sm text-yellow-200/80">
                Only the first {summary.appliedLimit.toLocaleString()} repos will be
                synced due to system limits. {summary.totalRepos - summary.cappedRepos}{" "}
                repos will be excluded.
              </div>
            </div>
          </div>
        )}

        {/* Collections Summary */}
        {summary.collectionsSummary.length > 0 && (
          <div>
            <h3 className="text-sm font-medium text-zinc-400 mb-3">Collections Breakdown</h3>
            <div className="space-y-4">
              {/* Primary Collections */}
              {summary.collectionsSummary.filter((c: { isExternal: boolean }) => !c.isExternal).length > 0 && (
                <div>
                  <h4 className="text-xs font-medium text-zinc-500 mb-2">Primary Collections</h4>
                  <div className="space-y-1 ml-4">
                    {summary.collectionsSummary
                      .filter((c: { isExternal: boolean }) => !c.isExternal)
                      .map((col: { collection: string; estimatedRepos: number; isExternal: boolean }) => (
                        <div
                          key={col.collection}
                          className="flex items-center py-1"
                        >
                          <span className="text-sm text-zinc-400 font-mono">
                            {col.collection}
                          </span>
                          <div className="flex-1 border-b border-dotted border-zinc-700 mx-2 self-end mb-1"></div>
                          <span className="text-sm text-zinc-500">
                            {col.estimatedRepos.toLocaleString()} repos
                          </span>
                        </div>
                      ))}
                  </div>
                </div>
              )}

              {/* External Collections */}
              {summary.collectionsSummary.filter((c: { isExternal: boolean }) => c.isExternal).length > 0 && (
                <div>
                  <h4 className="text-xs font-medium text-zinc-500 mb-2">External Collections</h4>
                  <div className="space-y-1 ml-4">
                    {summary.collectionsSummary
                      .filter((c: { isExternal: boolean }) => c.isExternal)
                      .map((col: { collection: string; estimatedRepos: number; isExternal: boolean }) => (
                        <div
                          key={col.collection}
                          className="flex items-center py-1"
                        >
                          <span className="text-sm text-zinc-400 font-mono">
                            {col.collection}
                          </span>
                          <div className="flex-1 border-b border-dotted border-zinc-700 mx-2 self-end mb-1"></div>
                          <span className="text-sm text-zinc-600 italic">
                            External data
                          </span>
                        </div>
                      ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        )}

        {/* Actions */}
        <div className="flex items-center justify-end gap-3 pt-4 border-t border-zinc-800">
          <Button
            onClick={onClose}
            disabled={isConfirming}
            size="md"
          >
            Cancel
          </Button>
          <Button
            onClick={onConfirm}
            disabled={isConfirming}
            variant="primary"
            size="md"
            className="flex items-center gap-2 bg-blue-600 hover:bg-blue-700 disabled:bg-zinc-700 text-white"
          >
            <Play size={16} />
            {isConfirming ? "Starting..." : "Start Sync"}
          </Button>
        </div>
      </div>
    </Dialog>
  );
}
