import { useState } from "react";
import { getSchemas, getTables, startMigration, getProgress } from "../api";

export default function MySQLMySQLMigrator() {
  const [srcHost, setSrcHost] = useState("");
  const [srcUser, setSrcUser] = useState("");
  const [srcPass, setSrcPass] = useState("");
  const [schemas, setSchemas] = useState([]);
  const [selectedSchemas, setSelectedSchemas] = useState([]);
  const [destHost, setDestHost] = useState("");
  const [destUser, setDestUser] = useState("");
  const [destPass, setDestPass] = useState("");
  const [progress, setProgress] = useState({ percent: 0, message: "Waiting to start..." });
  const [loading, setLoading] = useState(false);

  const loadSchemas = async () => {
    setLoading(true);
    try {
      const data = await getSchemas("mysql_mysql", { host: srcHost, user: srcUser, pass: srcPass });
      setSchemas(data.schemas || []);
      if (data.error) {
        alert("Error loading databases: " + data.error);
      }
    } catch {
      setSchemas([]);
    } finally {
      setLoading(false);
    }
  };

  const handleMigration = async () => {
    const payload = {
      SRC_HOST: srcHost,
      SRC_USER: srcUser,
      SRC_PASS: srcPass,
      DEST_HOST: destHost,
      DEST_USER: destUser,
      DEST_PASS: destPass,
      DATABASES: selectedSchemas
    };
    try {
      const data = await startMigration("mysql_mysql", payload);
      if (data.success) {
        pollProgress();
      } else {
        alert("Migration failed: " + (data.error || "Unknown error"));
      }
    } catch (error) {
      console.error("Error starting migration:", error);
      alert("Connection error: " + error.message);
    }
  };

  const pollProgress = async () => {
    try {
      const data = await getProgress("mysql_mysql");
      setProgress(data);
      if (data.status === "error") {
        alert("Migration error: " + (data.message || "Unknown error"));
      } else if (data.percent < 100 && data.status !== "completed") {
        setTimeout(pollProgress, 2000);
      }
    } catch (error) {
      console.error("Error polling progress:", error);
      setTimeout(pollProgress, 2000);
    }
  };

  return (
    <div className="space-y-8">
      <div className="text-center">
        <h2 className="text-2xl font-bold text-gray-900 dark:text-gray-100 mb-2">
          MySQL → MySQL Migration
        </h2>
        <p className="text-gray-600 dark:text-gray-400">
          Migrate complete MySQL databases .
        </p>
      </div>

      <div className="grid md:grid-cols-2 gap-8">
        {/* Source Database */}
        <div className="bg-gray-50 dark:bg-gray-700 p-6 rounded-lg">
          <h3 className="text-lg font-semibold mb-4 text-gray-900 dark:text-gray-100">
            Source Database
          </h3>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-1">Host</label>
              <input
                type="text"
                placeholder="e.g., localhost"
                value={srcHost}
                onChange={e => setSrcHost(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Username</label>
              <input
                type="text"
                placeholder="e.g., root"
                value={srcUser}
                onChange={e => setSrcUser(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Password</label>
              <input
                type="password"
                placeholder="Enter password"
                value={srcPass}
                onChange={e => setSrcPass(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
            <button
              onClick={loadSchemas}
              disabled={loading}
              className="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white font-medium py-2 px-4 rounded-md transition-colors"
            >
              {loading ? "Loading..." : "Load Databases"}
            </button>
            {schemas.length > 0 && (
              <div>
                <label className="block text-sm font-medium mb-1">Select Databases</label>
                <select
                  multiple
                  value={selectedSchemas}
                  onChange={e => setSelectedSchemas([...e.target.selectedOptions].map(o => o.value))}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent h-32"
                >
                  {schemas.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
              </div>
            )}
          </div>
        </div>

        {/* Target Database */}
        <div className="bg-gray-50 dark:bg-gray-700 p-6 rounded-lg">
          <h3 className="text-lg font-semibold mb-4 text-gray-900 dark:text-gray-100">
            Target Database
          </h3>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-1">Host</label>
              <input
                type="text"
                placeholder="e.g., localhost"
                value={destHost}
                onChange={e => setDestHost(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Username</label>
              <input
                type="text"
                placeholder="e.g., root"
                value={destUser}
                onChange={e => setDestUser(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Password</label>
              <input
                type="password"
                placeholder="Enter password"
                value={destPass}
                onChange={e => setDestPass(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
          </div>
        </div>
      </div>

      {/* Migration Button */}
      <div className="text-center">
        <button
          onClick={handleMigration}
          disabled={selectedSchemas.length === 0}
          className="bg-green-600 hover:bg-green-700 disabled:bg-gray-400 text-white font-medium py-3 px-8 rounded-md transition-colors text-lg"
        >
          Start Migration
        </button>
      </div>

      {/* Progress */}
      <div className="bg-gray-50 dark:bg-gray-700 p-6 rounded-lg">
        <h4 className="text-lg font-semibold mb-4 text-gray-900 dark:text-gray-100">Progress</h4>
        <div className="bg-gray-200 dark:bg-gray-600 rounded-full h-4 mb-4">
          <div
            className="bg-blue-600 h-4 rounded-full transition-all duration-300"
            style={{ width: `${progress.percent}%` }}
          ></div>
        </div>
        <pre className="bg-gray-800 text-green-400 p-4 rounded-md overflow-auto text-sm">
          {JSON.stringify(progress, null, 2)}
        </pre>
      </div>
    </div>
  );
}