"use client";

import { useState, useRef } from "react";
import type { Repository } from "@/hooks/useRepositories";

interface RepositoryModalProps {
  repositories: Repository[];
  onAdd: (data: {
    name: string;
    source_type: "path" | "zip" | "git";
    description?: string;
    source_path?: string;
    git_url?: string;
    zip_file?: File;
  }) => Promise<Repository>;
  onDelete: (id: string) => Promise<void>;
  onClose: () => void;
}

type Tab = "path" | "zip" | "git";

export function RepositoryModal({ repositories, onAdd, onDelete, onClose }: RepositoryModalProps) {
  const [tab, setTab] = useState<Tab>("path");
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [path, setPath] = useState("");
  const [gitUrl, setGitUrl] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);
  const fileRef = useRef<HTMLInputElement>(null);

  const resetForm = () => {
    setName(""); setDescription(""); setPath(""); setGitUrl("");
    setError(null);
    if (fileRef.current) fileRef.current.value = "";
  };

  const handleSubmit = async () => {
    if (!name.trim()) { setError("Name is required"); return; }
    setSubmitting(true);
    setError(null);
    try {
      if (tab === "path") {
        if (!path.trim()) { setError("Path is required"); setSubmitting(false); return; }
        await onAdd({ name, source_type: "path", description, source_path: path });
      } else if (tab === "zip") {
        const file = fileRef.current?.files?.[0];
        if (!file) { setError("Select a zip file"); setSubmitting(false); return; }
        await onAdd({ name, source_type: "zip", description, zip_file: file });
      } else {
        if (!gitUrl.trim()) { setError("Git URL is required"); setSubmitting(false); return; }
        await onAdd({ name, source_type: "git", description, git_url: gitUrl });
      }
      resetForm();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed");
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (id: string) => {
    await onDelete(id);
    setDeleteConfirm(null);
  };

  const SOURCE_TYPE_LABELS: Record<string, string> = { path: "Path", zip: "Zip", git: "Git" };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30" onClick={onClose}>
      <div className="bg-rp-surface rounded-xl w-full max-w-md max-h-[80vh] overflow-y-auto shadow-2xl" onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between px-5 py-4">
          <h2 className="text-rp-text font-semibold text-r-sm">Manage Repositories</h2>
          <button onClick={onClose} className="text-rp-muted hover:text-rp-text p-1">
            <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><path d="M5 5L13 13M13 5L5 13"/></svg>
          </button>
        </div>

        {repositories.length > 0 && (
          <div className="px-5 py-3">
            <p className="text-rp-muted text-r-2xs tracking-wider mb-2">Repositories</p>
            <div className="space-y-1">
              {repositories.map(r => (
                <div key={r.id} className="flex items-center justify-between px-3 py-2 rounded-lg hover:bg-rp-surface-alt/50 group">
                  <div className="min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="text-rp-text text-r-sm truncate">{r.name}</span>
                      <span className="text-r-2xs px-1.5 py-0.5 bg-rp-border/30 rounded text-rp-muted">{SOURCE_TYPE_LABELS[r.source_type]}</span>
                    </div>
                    <p className="text-rp-muted text-r-2xs truncate">{r.source_origin}</p>
                  </div>
                  {deleteConfirm === r.id ? (
                    <span className="text-r-2xs text-rp-error shrink-0 flex items-center gap-2">
                      <button onClick={() => handleDelete(r.id)} className="hover:underline">Delete</button>
                      <span className="text-rp-muted">·</span>
                      <button onClick={() => setDeleteConfirm(null)} className="text-rp-muted hover:underline">Cancel</button>
                    </span>
                  ) : (
                    <button
                      onClick={() => setDeleteConfirm(r.id)}
                      className="opacity-0 group-hover:opacity-100 text-rp-muted hover:text-rp-error p-1 transition-opacity shrink-0"
                    >
                      <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><path d="M2 4h10M5 4V3a1 1 0 011-1h2a1 1 0 011 1v1M9 6v5M5 6v5M3 4l.5 7.5a1 1 0 001 .5h5a1 1 0 001-.5L11 4"/></svg>
                    </button>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        <div className="px-5 py-4">
          <p className="text-rp-muted text-r-2xs tracking-wider mb-3">Add repository</p>

          <div className="tab-bar mb-4 border-b border-rp-border/10">
            {(["path", "zip", "git"] as Tab[]).map(t => (
              <button
                key={t}
                onClick={() => { setTab(t); setError(null); }}
                className={`tab-btn ${tab === t ? "active" : ""}`}
              >
                {t === "path" ? "Local Path" : t === "zip" ? "Upload Zip" : "Git Clone"}
              </button>
            ))}
          </div>

          <div className="space-y-3">
            <input
              placeholder="Repository name"
              value={name}
              onChange={e => setName(e.target.value)}
              className="w-full px-3 py-2 bg-rp-surface-alt border border-rp-border/40 rounded-lg text-rp-text text-r-sm placeholder:text-rp-muted/50 focus:outline-none focus:border-rp-accent/30"
            />
            <input
              placeholder="Description (optional)"
              value={description}
              onChange={e => setDescription(e.target.value)}
              className="w-full px-3 py-2 bg-rp-surface-alt border border-rp-border/40 rounded-lg text-rp-text text-r-sm placeholder:text-rp-muted/50 focus:outline-none focus:border-rp-accent/30"
            />

            {tab === "path" && (
              <input
                placeholder="/path/to/repository"
                value={path}
                onChange={e => setPath(e.target.value)}
                className="w-full px-3 py-2 bg-rp-surface-alt border border-rp-border/40 rounded-lg text-rp-text text-r-sm font-mono placeholder:text-rp-muted/50 focus:outline-none focus:border-rp-accent/30"
              />
            )}

            {tab === "zip" && (
              <input ref={fileRef} type="file" accept=".zip" className="w-full text-r-sm text-rp-muted file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border file:border-rp-border/50 file:bg-rp-surface-alt file:text-rp-text file:text-r-xs" />
            )}

            {tab === "git" && (
              <input
                placeholder="https://github.com/user/repo.git"
                value={gitUrl}
                onChange={e => setGitUrl(e.target.value)}
                className="w-full px-3 py-2 bg-rp-surface-alt border border-rp-border/40 rounded-lg text-rp-text text-r-sm font-mono placeholder:text-rp-muted/50 focus:outline-none focus:border-rp-accent/30"
              />
            )}

            {error && <p className="text-rp-error text-r-xs">{error}</p>}

            <button
              onClick={handleSubmit}
              disabled={submitting}
              className="btn-accent w-full disabled:opacity-50"
            >
              {submitting ? "Adding..." : "Add Repository"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
