"use client";

import { useState, useRef } from "react";
import { Upload, X, CheckCircle2, XCircle, FileText, Download, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import type { Network } from "@/lib/types";

interface ValidatedRow {
  row: number;
  status: "valid" | "invalid";
  content?: string;
  track?: string;
  scheduledAt?: string;
  networks?: string[];
  tags?: string[];
  notes?: string;
  errors?: string[];
}

interface ValidationResult {
  valid: number;
  invalid: number;
  rows: ValidatedRow[];
}

interface BulkImportModalProps {
  open: boolean;
  onClose: () => void;
  onComplete: () => void;
}

type Step = "upload" | "preview" | "importing" | "done";

export function BulkImportModal({ open, onClose, onComplete }: BulkImportModalProps) {
  const fileRef = useRef<HTMLInputElement>(null);
  const [file, setFile] = useState<File | null>(null);
  const [step, setStep] = useState<Step>("upload");
  const [validating, setValidating] = useState(false);
  const [validation, setValidation] = useState<ValidationResult | null>(null);
  const [progress, setProgress] = useState({ done: 0, total: 0 });
  const [results, setResults] = useState<{ scheduled: number; skipped: { row: number; error: string }[] } | null>(null);

  if (!open) return null;

  const validRows = validation?.rows.filter((r) => r.status === "valid") ?? [];
  const invalidRows = validation?.rows.filter((r) => r.status === "invalid") ?? [];

  const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
    const f = e.target.files?.[0];
    if (!f) return;
    setFile(f);
    setValidation(null);
    setResults(null);
    setStep("upload");
  };

  const handleValidate = async () => {
    if (!file) return;
    setValidating(true);
    try {
      const formData = new FormData();
      formData.append("file", file);
      const res = await fetch("/api/v1/bulk/validate", {
        method: "POST",
        body: formData,
      });
      if (!res.ok) {
        const data = await res.json();
        alert(data.error || "Validation failed");
        return;
      }
      const data: ValidationResult = await res.json();
      setValidation(data);
      setStep("preview");
    } catch {
      alert("Network error during validation");
    } finally {
      setValidating(false);
    }
  };

  const handleImport = async () => {
    if (validRows.length === 0) return;
    setStep("importing");
    setProgress({ done: 0, total: validRows.length });

    const scheduled: number[] = [];
    const skipped: { row: number; error: string }[] = [];

    for (let i = 0; i < validRows.length; i++) {
      const row = validRows[i];
      try {
        const res = await fetch("/api/v1/posts", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            content: row.content,
            networks: row.networks as Network[],
            scheduledAt: row.scheduledAt,
            tags: row.tags ?? [],
            track: row.track,
            notes: row.notes,
            source: "HUMAN",
          }),
        });
        if (!res.ok) {
          const data = await res.json();
          skipped.push({ row: row.row, error: data.error || "API error" });
        } else {
          scheduled.push(row.row);
        }
      } catch {
        skipped.push({ row: row.row, error: "Network error" });
      }
      setProgress({ done: i + 1, total: validRows.length });
    }

    setResults({ scheduled: scheduled.length, skipped });
    setStep("done");
    if (scheduled.length > 0) onComplete();
  };

  const handleClose = () => {
    setFile(null);
    setStep("upload");
    setValidation(null);
    setResults(null);
    setProgress({ done: 0, total: 0 });
    if (fileRef.current) fileRef.current.value = "";
    onClose();
  };

  const handleBack = () => {
    setStep("upload");
    setValidation(null);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="w-full max-w-3xl max-h-[85vh] bg-white rounded-xl shadow-xl flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b">
          <h2 className="text-lg font-semibold text-gray-900">Bulk Import Posts</h2>
          <button onClick={handleClose} className="text-gray-400 hover:text-gray-600">
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto px-6 py-4 space-y-4">
          {/* Step 1: Upload */}
          {(step === "upload" || step === "preview") && (
            <>
              {/* Template download + file upload */}
              <div className="flex items-center gap-3">
                <a
                  href="/api/v1/bulk/template"
                  download="pingcap-social-template.csv"
                  className="inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium text-blue-700 bg-blue-50 border border-blue-200 rounded-lg hover:bg-blue-100 transition-colors"
                >
                  <Download className="h-4 w-4" />
                  Download Template
                </a>
                <div className="flex-1">
                  <input
                    ref={fileRef}
                    type="file"
                    accept=".csv"
                    onChange={handleFile}
                    className="hidden"
                  />
                  <Button
                    variant="outline"
                    onClick={() => fileRef.current?.click()}
                    className="w-full border-dashed border-gray-300 text-gray-600 hover:bg-gray-50"
                  >
                    <Upload className="h-4 w-4 mr-2" />
                    {file ? file.name : "Upload CSV file"}
                  </Button>
                </div>
              </div>
              <p className="text-[11px] text-gray-400">
                CSV columns: content, track, scheduledAt, networks, tags, notes
              </p>
            </>
          )}

          {/* Validate button (step 1 → step 2) */}
          {step === "upload" && file && !validating && (
            <Button
              onClick={handleValidate}
              className="w-full bg-blue-600 hover:bg-blue-700 text-white"
            >
              Validate CSV
            </Button>
          )}
          {validating && (
            <div className="flex items-center justify-center gap-2 py-3 text-sm text-gray-500">
              <Loader2 className="h-4 w-4 animate-spin" />
              Validating rows...
            </div>
          )}

          {/* Step 2: Preview validation results */}
          {step === "preview" && validation && (
            <>
              {/* Summary bar */}
              <div className="flex items-center gap-3 px-4 py-3 rounded-lg bg-gray-50 border text-sm">
                <span className="text-green-700 font-medium">{validation.valid} valid</span>
                <span className="text-gray-300">|</span>
                <span className="text-red-600 font-medium">{validation.invalid} invalid</span>
                <span className="text-gray-300">|</span>
                <span className="text-gray-500">{validation.rows.length} total rows</span>
                {validation.invalid > 0 && (
                  <span className="ml-auto text-xs text-gray-400">
                    Fix errors and re-upload, or import valid rows only
                  </span>
                )}
              </div>

              {/* Validation table */}
              <div className="border rounded-lg overflow-hidden">
                <div className="max-h-72 overflow-y-auto">
                  <table className="w-full text-xs">
                    <thead className="bg-gray-50 sticky top-0">
                      <tr>
                        <th className="px-3 py-2 text-left text-gray-500 font-medium w-8">#</th>
                        <th className="px-3 py-2 text-left text-gray-500 font-medium">Content</th>
                        <th className="px-3 py-2 text-left text-gray-500 font-medium w-24">Track</th>
                        <th className="px-3 py-2 text-left text-gray-500 font-medium w-24">Networks</th>
                        <th className="px-3 py-2 text-left text-gray-500 font-medium w-36">Scheduled</th>
                        <th className="px-3 py-2 text-center text-gray-500 font-medium w-16">Status</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      {validation.rows.map((row) => (
                        <tr key={row.row} className={row.status === "valid" ? "bg-green-50/30" : "bg-red-50/50"}>
                          <td className="px-3 py-2 text-gray-400">{row.row}</td>
                          <td className="px-3 py-2 text-gray-700 truncate max-w-[220px]">
                            {row.content || <span className="text-gray-300 italic">empty</span>}
                          </td>
                          <td className="px-3 py-2 text-gray-500">{row.track || "—"}</td>
                          <td className="px-3 py-2 text-gray-500">{row.networks?.join(", ") || "—"}</td>
                          <td className="px-3 py-2 text-gray-500">
                            {row.scheduledAt
                              ? new Date(row.scheduledAt).toLocaleString(undefined, { timeZoneName: 'short' })
                              : "—"}
                          </td>
                          <td className="px-3 py-2 text-center">
                            {row.status === "valid" ? (
                              <CheckCircle2 className="h-4 w-4 text-green-500 mx-auto" />
                            ) : (
                              <span className="flex items-center gap-1 text-red-600">
                                <XCircle className="h-4 w-4 shrink-0" />
                                <span className="truncate text-[10px]">{row.errors?.join("; ")}</span>
                              </span>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </>
          )}

          {/* Step 3: Progress bar during import */}
          {step === "importing" && (
            <div className="space-y-2 py-4">
              <div className="h-2 rounded-full bg-gray-200 overflow-hidden">
                <div
                  className="h-full rounded-full bg-blue-500 transition-all"
                  style={{ width: `${(progress.done / progress.total) * 100}%` }}
                />
              </div>
              <p className="text-xs text-gray-500 text-center">
                Importing {progress.done}/{progress.total}...
              </p>
            </div>
          )}

          {/* Step 4: Done */}
          {step === "done" && results && (
            <div className="rounded-lg border p-4 space-y-2">
              <div className="flex items-center gap-2">
                <FileText className="h-5 w-5 text-gray-400" />
                <span className="text-sm font-medium text-gray-900">Import Complete</span>
              </div>
              <p className="text-sm text-green-700">
                {results.scheduled} post{results.scheduled !== 1 ? "s" : ""} scheduled
              </p>
              {results.skipped.length > 0 && (
                <div className="text-sm text-red-600 space-y-0.5">
                  <p>{results.skipped.length} skipped:</p>
                  {results.skipped.map((s) => (
                    <p key={s.row} className="text-xs ml-2">Row {s.row}: {s.error}</p>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between px-6 py-4 border-t">
          <div>
            {step === "preview" && (
              <Button variant="outline" onClick={handleBack} className="text-gray-600">
                Back
              </Button>
            )}
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" onClick={handleClose}>
              {step === "done" ? "Close" : "Cancel"}
            </Button>
            {step === "preview" && validRows.length > 0 && (
              <Button
                onClick={handleImport}
                className="bg-gray-900 hover:bg-gray-800 text-white"
              >
                Import {validRows.length} Valid Post{validRows.length !== 1 ? "s" : ""}
              </Button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
