"use client";

import React, { useState } from "react";
import {
  FlaskConical,
  Play,
  CheckCircle2,
  AlertCircle,
  ExternalLink,
  Code,
  Eye,
  ShieldCheck,
  Sparkles,
  ArrowRight,
} from "lucide-react";

export const TestModeView: React.FC = () => {
  const [testName, setTestName] = useState("Md. Test Rahim");
  const [testMobile, setTestMobile] = useState("01799887766");
  const [testType, setTestType] = useState("New");
  const [testGender, setTestGender] = useState("Male");
  const [running, setRunning] = useState(false);
  const [testResult, setTestResult] = useState<any | null>(null);

  const handleRunTest = async () => {
    setRunning(true);
    setTestResult(null);

    try {
      const res = await fetch("/api/jobs/test", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          customData: {
            name: testName,
            mobile: testMobile,
            type: testType,
            gender: testGender,
          },
        }),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Test execution failed");
      setTestResult(data.result);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Error";
      alert(msg);
    } finally {
      setRunning(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h2 className="text-xl font-extrabold text-white flex items-center gap-2">
          <FlaskConical className="w-5 h-5 text-purple-400" />
          Test Automation Engine &amp; Form Inspector
        </h2>
        <p className="text-xs text-slate-400 mt-0.5">
          Safely test the Playwright form-filling sequence without submitting. Verify selector accuracy and inspect captured DOM elements.
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Left: Test Form Configuration */}
        <div className="p-6 rounded-2xl bg-slate-900 border border-slate-800 shadow-xl space-y-4">
          <h3 className="text-sm font-bold text-white flex items-center gap-2 pb-2 border-b border-slate-800">
            <ShieldCheck className="w-4 h-4 text-emerald-400" />
            Test Form Parameters (Safe Mode)
          </h3>

          <div className="p-3.5 rounded-xl bg-purple-950/30 border border-purple-700/40 text-xs text-purple-200">
            <strong className="text-purple-300">Safe Test Guarantee:</strong> The automation worker will open the external appointment page, populate all fields using your configured selectors, and stop right before clicking submit.
          </div>

          <div className="space-y-3">
            <div>
              <label className="block text-xs font-semibold text-slate-300 mb-1">Test Patient Name</label>
              <input
                type="text"
                value={testName}
                onChange={(e) => setTestName(e.target.value)}
                className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white focus:outline-none focus:border-purple-500"
              />
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-300 mb-1">Test Mobile Number</label>
              <input
                type="text"
                value={testMobile}
                onChange={(e) => setTestMobile(e.target.value)}
                className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs font-mono text-white focus:outline-none focus:border-purple-500"
              />
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Patient Type</label>
                <select
                  value={testType}
                  onChange={(e) => setTestType(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white focus:outline-none focus:border-purple-500"
                >
                  <option value="New">New</option>
                  <option value="Follow Up">Follow Up</option>
                  <option value="Report">Report</option>
                </select>
              </div>

              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Gender</label>
                <select
                  value={testGender}
                  onChange={(e) => setTestGender(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white focus:outline-none focus:border-purple-500"
                >
                  <option value="Male">Male</option>
                  <option value="Female">Female</option>
                </select>
              </div>
            </div>

            <button
              onClick={handleRunTest}
              disabled={running}
              className="w-full mt-4 py-3 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-white rounded-xl text-xs font-bold flex items-center justify-center gap-2 shadow-lg shadow-purple-600/30 disabled:opacity-50 transition-all hover:scale-[1.01]"
            >
              <FlaskConical className={`w-4 h-4 ${running ? "animate-spin" : ""}`} />
              <span>{running ? "Simulating Browser & Inspecting Selectors..." : "Run Test Form Inspection"}</span>
            </button>
          </div>
        </div>

        {/* Right: Step By Step Execution Trace */}
        <div className="p-6 rounded-2xl bg-slate-900 border border-slate-800 shadow-xl flex flex-col justify-between">
          <div>
            <h3 className="text-sm font-bold text-white flex items-center gap-2 pb-2 border-b border-slate-800 mb-4">
              <Code className="w-4 h-4 text-cyan-400" />
              Automated Step-by-Step Validation Trace
            </h3>

            {testResult ? (
              <div className="space-y-3">
                {testResult.executionSteps?.map((step: any, idx: number) => (
                  <div
                    key={idx}
                    className="p-3 rounded-xl bg-slate-950/80 border border-slate-800 flex items-start gap-3"
                  >
                    <div className="mt-0.5">
                      {step.status === "done" && <CheckCircle2 className="w-4 h-4 text-emerald-400" />}
                      {step.status === "skipped" && <Sparkles className="w-4 h-4 text-amber-400" />}
                      {step.status === "failed" && <AlertCircle className="w-4 h-4 text-rose-400" />}
                    </div>
                    <div className="flex-1">
                      <div className="flex items-center justify-between text-xs">
                        <span className="font-bold text-slate-200">{step.step}</span>
                        <span className="text-[10px] text-slate-500 font-mono">{step.timestamp}</span>
                      </div>
                      {step.details && <p className="text-[11px] text-slate-400 mt-0.5">{step.details}</p>}
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-12 text-slate-500 space-y-2">
                <FlaskConical className="w-10 h-10 mx-auto opacity-30 text-purple-400" />
                <p className="text-xs">Click &quot;Run Test Form Inspection&quot; to execute live test workflow.</p>
              </div>
            )}
          </div>

          {testResult?.screenshotUrl && (
            <div className="mt-6 pt-4 border-t border-slate-800">
              <div className="text-xs font-bold text-slate-300 mb-2 flex items-center gap-1.5">
                <Eye className="w-3.5 h-3.5 text-blue-400" />
                Rendered Form Inspection Preview
              </div>
              <div className="rounded-xl border border-slate-700 overflow-hidden bg-slate-950">
                <img src={testResult.screenshotUrl} alt="Test Result" className="w-full h-auto block" />
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
