import { useState } from 'react';

export default function Calculator() {
  const [displayValue, setDisplayValue] = useState('0');
  const [firstOperand, setFirstOperand] = useState(null);
  const [operator, setOperator] = useState(null);
  const [waitingForSecondOperand, setWaitingForSecondOperand] = useState(false);

  const inputDigit = (digit) => {
    if (waitingForSecondOperand) {
      setDisplayValue(String(digit));
      setWaitingForSecondOperand(false);
    } else {
      setDisplayValue(displayValue === '0' ? String(digit) : displayValue + digit);
    }
  };

  const inputDecimal = () => {
    if (waitingForSecondOperand) {
      setDisplayValue('0.');
      setWaitingForSecondOperand(false);
      return;
    }

    if (!displayValue.includes('.')) {
      setDisplayValue(displayValue + '.');
    }
  };

  const clearDisplay = () => {
    setDisplayValue('0');
    setFirstOperand(null);
    setOperator(null);
    setWaitingForSecondOperand(false);
  };

  const performOperation = (nextOperator) => {
    const inputValue = parseFloat(displayValue);

    if (firstOperand === null) {
      setFirstOperand(inputValue);
    } else if (operator) {
      const result = calculate(firstOperand, inputValue, operator);
      setDisplayValue(String(result));
      setFirstOperand(result);
    }

    setWaitingForSecondOperand(true);
    setOperator(nextOperator);
  };

  const calculate = (firstOperand, secondOperand, operator) => {
    switch (operator) {
      case '+':
        return firstOperand + secondOperand;
      case '-':
        return firstOperand - secondOperand;
      case '*':
        return firstOperand * secondOperand;
      case '/':
        return firstOperand / secondOperand;
      default:
        return secondOperand;
    }
  };

  const handleEquals = () => {
    if (!operator || firstOperand === null) return;

    const inputValue = parseFloat(displayValue);
    const result = calculate(firstOperand, inputValue, operator);

    setDisplayValue(String(result));
    setFirstOperand(null);
    setOperator(null);
    setWaitingForSecondOperand(false);
  };

  return (
    <div className="w-full max-w-md mx-auto bg-calc-bg rounded-xl shadow-lg overflow-hidden">
      <div className="p-4">
        <div className="text-right mb-4">
          <a
            href="https://huggingface.co/spaces/akhaliq/anycoder"
            target="_blank"
            rel="noopener noreferrer"
            className="text-sm text-gray-500 hover:text-gray-700 transition-colors"
          >
            Built with anycoder
          </a>
        </div>

        <div className="bg-calc-display rounded-lg p-6 mb-4 text-right">
          <div className="text-4xl font-light text-gray-800 overflow-hidden">
            {displayValue}
          </div>
        </div>

        <div className="grid grid-cols-4 gap-2">
          {['7', '8', '9', '/'].map((btn) => (
            <button
              key={btn}
              className={`p-4 rounded-lg text-xl font-medium transition-colors ${
                isNaN(btn)
                  ? 'bg-calc-btn-operator hover:bg-calc-btn-operator-hover active:bg-calc-btn-operator-active text-white'
                  : 'bg-calc-btn hover:bg-calc-btn-hover active:bg-calc-btn-active text-gray-800'
              }`}
              onClick={() => isNaN(btn) ? performOperation(btn) : inputDigit(btn)}
            >
              {btn}
            </button>
          ))}

          {['4', '5', '6', '*'].map((btn) => (
            <button
              key={btn}
              className={`p-4 rounded-lg text-xl font-medium transition-colors ${
                isNaN(btn)
                  ? 'bg-calc-btn-operator hover:bg-calc-btn-operator-hover active:bg-calc-btn-operator-active text-white'
                  : 'bg-calc-btn hover:bg-calc-btn-hover active:bg-calc-btn-active text-gray-800'
              }`}
              onClick={() => isNaN(btn) ? performOperation(btn) : inputDigit(btn)}
            >
              {btn}
            </button>
          ))}

          {['1', '2', '3', '-'].map((btn) => (
            <button
              key={btn}
              className={`p-4 rounded-lg text-xl font-medium transition-colors ${
                isNaN(btn)
                  ? 'bg-calc-btn-operator hover:bg-calc-btn-operator-hover active:bg-calc-btn-operator-active text-white'
                  : 'bg-calc-btn hover:bg-calc-btn-hover active:bg-calc-btn-active text-gray-800'
              }`}
              onClick={() => isNaN(btn) ? performOperation(btn) : inputDigit(btn)}
            >
              {btn}
            </button>
          ))}

          {['0', '.', '=', '+'].map((btn) => (
            <button
              key={btn}
              className={`p-4 rounded-lg text-xl font-medium transition-colors ${
                btn === '='
                  ? 'bg-calc-btn-operator hover:bg-calc-btn-operator-hover active:bg-calc-btn-operator-active text-white'
                  : isNaN(btn)
                  ? 'bg-calc-btn hover:bg-calc-btn-hover active:bg-calc-btn-active text-gray-800'
                  : 'bg-calc-btn hover:bg-calc-btn-hover active:bg-calc-btn-active text-gray-800 col-span-2'
              }`}
              onClick={() => {
                if (btn === '=') {
                  handleEquals();
                } else if (btn === '.') {
                  inputDecimal();
                } else if (isNaN(btn)) {
                  performOperation(btn);
                } else {
                  inputDigit(btn);
                }

            >
              {btn}
            </button>
          ))}

          <button
            className="col-span-4 p-4 rounded-lg text-xl font-medium bg-gray-400 hover:bg-gray-500 active:bg-gray-600 text-white transition-colors"
            onClick={clearDisplay}
          >
            AC
          </button>
        </div>
      </div>
    </div>
  );
}