import styles from "./CommitDialog.module.css";
import React, { useState } from "react";

import { Icon } from "../../ui/Icon";

interface CommitDialogProps {
  isOpen: boolean;
  filePath: string;
  originalContent: string;
  newContent: string;
  onCommit: (message: string) => Promise<void>;
  onCancel: () => void;
}

export const CommitDialog: React.FC<CommitDialogProps> = ({
  isOpen,
  filePath,
  originalContent,
  newContent,
  onCommit,
  onCancel,
}) => {
  const [message, setMessage] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(">");

  if (!isOpen) return null;

  const generateDiff = () => {
    const originalLines = originalContent.split("\n");
    const newLines = newContent.split("\n");
    const maxLines = Math.max(originalLines.length, newLines.length);
    const diff: { type: "same" | "added" | "removed"; line: string; lineNum: number }[] = [];

    for (let i = 0; i < maxLines; i++) {
      const original = originalLines[i] || "";
      const updated = newLines[i] || "";

      if (original === updated) {
        diff.push({ type: "same", line: updated, lineNum: i + 1 });
      } else {
        if (original) {
          diff.push({ type: "removed", line: original, lineNum: i + 1 });
        }
        if (updated) {
          diff.push({ type: "added", line: updated, lineNum: i + 1 });
        }
      }
    }

    return diff;
  };

  const handleCommit = async () => {
    if (!message.trim()) {
      setError("Please enter a commit message");
      return;
    }

    setLoading(true);
    setError("");
    try {
      await onCommit(message);
    } catch {
      setError("Failed to commit changes");
    } finally {
      setLoading(false);
    }
  };

  const diff = generateDiff();
  const hasChanges = diff.some((d) => d.type !== "same");

  return (
    <div className={styles.dialogOverlay}>
      <div className={styles.commitDialog}>
        <div className={styles.dialogHeader}>
          <h3>Commit Changes</h3>
          <button className={styles.dialogClose} onClick={onCancel} type="button">
            ×
          </button>
        </div>

        <div className={styles.dialogBody}>
          <p className={styles.fileInfo}>
            Editing: <strong>{filePath}</strong>
          </p>

          {!hasChanges && (
            <div className={styles.warningMessage}>No changes to commit</div>
          )}

          {hasChanges && (
            <div className={styles.diffPreview}>
              <h4>Changes</h4>
              <div className={styles.diffContent}>
                {diff.map((line, i) => (
                  <div
                    key={i}
                    className={`${styles.diffLine} ${line.type === "added" ? styles.diffAdded : line.type === "removed" ? styles.diffRemoved : styles.diffSame}`}
                  >
                    <span className={styles.diffLineNumber}>{line.lineNum}</span>
                    <span className={styles.diffMarker}>
                      {line.type === "added" && "+"}
                      {line.type === "removed" && "-"}
                      {line.type === "same" && " "}
                    </span>
                    <span className={styles.diffLineContent}>{line.line}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          <div className="form-group">
            <label>Commit Message *</label>
            <textarea
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              placeholder="Describe your changes..."
              rows={3}
              className="form-textarea"
            />
          </div>

          {error && <div className="error-message">{error}</div>}
        </div>

        <div className={styles.dialogFooter}>
          <button
            className="btn-secondary"
            onClick={onCancel}
            type="button"
          >
            <Icon name="cancel" size="sm" />
            Cancel
          </button>
          <button
            className="btn-primary"
            onClick={handleCommit}
            disabled={loading || !hasChanges || !message.trim()}
            type="button"
          >
            {loading ? (
              <>
                <Icon name="loading" size="sm" />
                Committing...
              </>
            ) : (
              <>
                <Icon name="commit" size="sm" />
                Commit Changes
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
};
