"use client";

import { useState, useCallback } from "react";
import {
  RefreshCw,
  Download,
  Upload,
  ArrowLeftRight,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Clock,
  FileText,
} from "lucide-react";
import { Button } from "@/shared/components/ui/button";
import { Badge } from "@/shared/components/ui/badge";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/shared/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/shared/components/ui/dialog";

interface SyncStatus {
  filePath: string;
  lastModified: string;
  totalLines: number;
  groups: number;
  syncPlan: {
    addToArchiTools: number;
    addToManicTime: number;
    unchanged: number;
    conflicts: string[];
  };
  archiToolsCount: number;
}

interface SyncResultData {
  success: boolean;
  direction: string;
  pulled: number;
  pushed: boolean;
  totalTags: number;
  warnings: string[];
  timestamp: string;
}

export function ManicTimeSyncPanel({
  onSyncComplete,
}: {
  onSyncComplete: () => void;
}) {
  const [status, setStatus] = useState<SyncStatus | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [syncing, setSyncing] = useState(false);
  const [syncResult, setSyncResult] = useState<SyncResultData | null>(null);
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const [pendingDirection, setPendingDirection] = useState<string>("");

  const checkStatus = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/manictime");
      if (!res.ok) {
        const data = (await res.json()) as { message?: string };
        setError(data.message ?? `Eroare HTTP ${res.status}`);
        setStatus(null);
        return;
      }
      const data = (await res.json()) as SyncStatus;
      setStatus(data);
    } catch (err) {
      setError(
        `Eroare de conexiune: ${err instanceof Error ? err.message : "necunoscută"}`,
      );
    } finally {
      setLoading(false);
    }
  }, []);

  const executeSync = useCallback(
    async (direction: string) => {
      setSyncing(true);
      setSyncResult(null);
      setError(null);
      try {
        const res = await fetch("/api/manictime", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ direction }),
        });
        if (!res.ok) {
          const data = (await res.json()) as { message?: string };
          setError(data.message ?? `Eroare HTTP ${res.status}`);
          return;
        }
        const data = (await res.json()) as SyncResultData;
        setSyncResult(data);
        onSyncComplete();
        // Refresh status
        await checkStatus();
      } catch (err) {
        setError(
          `Eroare de conexiune: ${err instanceof Error ? err.message : "necunoscută"}`,
        );
      } finally {
        setSyncing(false);
        setShowConfirmDialog(false);
      }
    },
    [checkStatus, onSyncComplete],
  );

  const handleSync = (direction: string) => {
    setPendingDirection(direction);
    setShowConfirmDialog(true);
  };

  return (
    <>
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-base">
            <FileText className="h-4 w-4" />
            Sincronizare ManicTime
            {status && (
              <Badge variant="outline" className="ml-auto text-xs">
                <Clock className="mr-1 h-3 w-3" />
                {new Date(status.lastModified).toLocaleString("ro-RO")}
              </Badge>
            )}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Check status button */}
          <div className="flex flex-wrap items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={checkStatus}
              disabled={loading}
            >
              <RefreshCw
                className={`mr-1.5 h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`}
              />
              {loading
                ? "Se verifică..."
                : status
                  ? "Reîmprospătează"
                  : "Verifică conexiunea"}
            </Button>

            {status && (
              <>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handleSync("pull")}
                  disabled={syncing}
                >
                  <Download className="mr-1.5 h-3.5 w-3.5" />
                  Import din ManicTime
                  {status.syncPlan.addToArchiTools > 0 && (
                    <Badge variant="secondary" className="ml-1.5">
                      +{status.syncPlan.addToArchiTools}
                    </Badge>
                  )}
                </Button>

                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handleSync("push")}
                  disabled={syncing}
                >
                  <Upload className="mr-1.5 h-3.5 w-3.5" />
                  Export în ManicTime
                  {status.syncPlan.addToManicTime > 0 && (
                    <Badge variant="secondary" className="ml-1.5">
                      +{status.syncPlan.addToManicTime}
                    </Badge>
                  )}
                </Button>

                <Button
                  size="sm"
                  onClick={() => handleSync("both")}
                  disabled={syncing}
                >
                  <ArrowLeftRight className="mr-1.5 h-3.5 w-3.5" />
                  {syncing ? "Se sincronizează..." : "Sincronizare completă"}
                </Button>
              </>
            )}
          </div>

          {/* Error */}
          {error && (
            <div className="flex items-start gap-2 rounded-md border border-destructive/50 bg-destructive/5 p-3">
              <XCircle className="mt-0.5 h-4 w-4 shrink-0 text-destructive" />
              <p className="text-sm text-destructive">{error}</p>
            </div>
          )}

          {/* Status info */}
          {status && (
            <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
              <div className="rounded-md border p-2.5 text-center">
                <p className="text-xs text-muted-foreground">
                  Etichete ManicTime
                </p>
                <p className="text-lg font-bold">{status.totalLines}</p>
              </div>
              <div className="rounded-md border p-2.5 text-center">
                <p className="text-xs text-muted-foreground">
                  Etichete ArchiTools
                </p>
                <p className="text-lg font-bold">{status.archiToolsCount}</p>
              </div>
              <div className="rounded-md border p-2.5 text-center">
                <p className="text-xs text-muted-foreground">
                  Noi din ManicTime
                </p>
                <p className="text-lg font-bold text-blue-600">
                  {status.syncPlan.addToArchiTools}
                </p>
              </div>
              <div className="rounded-md border p-2.5 text-center">
                <p className="text-xs text-muted-foreground">
                  Noi din ArchiTools
                </p>
                <p className="text-lg font-bold text-violet-600">
                  {status.syncPlan.addToManicTime}
                </p>
              </div>
            </div>
          )}

          {/* Sync result */}
          {syncResult && (
            <div className="flex items-start gap-2 rounded-md border border-green-200 bg-green-50 p-3 dark:border-green-800 dark:bg-green-950/30">
              <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0 text-green-600" />
              <div className="space-y-1">
                <p className="text-sm font-medium text-green-800 dark:text-green-200">
                  Sincronizare completă
                </p>
                <p className="text-xs text-green-700 dark:text-green-300">
                  {syncResult.pulled > 0 &&
                    `${syncResult.pulled} etichete importate din ManicTime. `}
                  {syncResult.pushed && "Fișierul Tags.txt a fost actualizat. "}
                  Total: {syncResult.totalTags} etichete.
                </p>
                {syncResult.warnings.length > 0 && (
                  <div className="mt-1 space-y-0.5">
                    {syncResult.warnings.map((w, i) => (
                      <p
                        key={i}
                        className="flex items-center gap-1 text-xs text-amber-700 dark:text-amber-300"
                      >
                        <AlertTriangle className="h-3 w-3" /> {w}
                      </p>
                    ))}
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Hint when no check performed */}
          {!status && !error && !loading && (
            <p className="text-xs text-muted-foreground">
              Apasă &ldquo;Verifică conexiunea&rdquo; pentru a vedea starea
              fișierului ManicTime Tags.txt. Fișierul este citit de pe share-ul
              SMB montat la{" "}
              <code className="rounded bg-muted px-1 text-[11px]">
                /mnt/manictime/Tags.txt
              </code>
              . Configurați calea prin variabila{" "}
              <code className="rounded bg-muted px-1 text-[11px]">
                MANICTIME_TAGS_PATH
              </code>
              .
            </p>
          )}
        </CardContent>
      </Card>

      {/* Confirmation dialog */}
      <Dialog open={showConfirmDialog} onOpenChange={setShowConfirmDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              {pendingDirection === "pull" && "Import din ManicTime"}
              {pendingDirection === "push" && "Export în ManicTime"}
              {pendingDirection === "both" && "Sincronizare completă"}
            </DialogTitle>
          </DialogHeader>
          <div className="space-y-3 py-2">
            {pendingDirection === "pull" && (
              <p className="text-sm text-muted-foreground">
                Se vor importa{" "}
                <strong>
                  {status?.syncPlan.addToArchiTools ?? 0} etichete noi
                </strong>{" "}
                din fișierul ManicTime în ArchiTools. Etichetele existente nu
                vor fi modificate.
              </p>
            )}
            {pendingDirection === "push" && (
              <p className="text-sm text-muted-foreground">
                Se va rescrie fișierul Tags.txt cu toate etichetele din
                ArchiTools. Un backup al versiunii curente va fi creat automat.
                ManicTime va primi{" "}
                <strong>
                  {status?.syncPlan.addToManicTime ?? 0} etichete noi
                </strong>
                .
              </p>
            )}
            {pendingDirection === "both" && (
              <p className="text-sm text-muted-foreground">
                Se vor importa mai întâi etichetele noi din ManicTime (
                <strong>{status?.syncPlan.addToArchiTools ?? 0}</strong>), apoi
                se va actualiza fișierul Tags.txt cu toate etichetele din
                ArchiTools. Backup automat inclus.
              </p>
            )}
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowConfirmDialog(false)}
            >
              Anulează
            </Button>
            <Button
              onClick={() => executeSync(pendingDirection)}
              disabled={syncing}
            >
              {syncing ? "Se sincronizează..." : "Confirmă"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
