import { useState, useMemo } from 'react';
import { Card, CardHeader } from '../../ui/Card';
import { Button } from '../../ui/Button';
import { Input } from '../../ui/Input';
import { CheckCircle, Info, TrendingUp } from 'lucide-react';

interface VisualizadorExcedentesProps {
  ejercicioId: string;
  onComplete?: (puntuacion: number) => void;
}

export function VisualizadorExcedentes({ ejercicioId: _ejercicioId, onComplete }: VisualizadorExcedentesProps) {
  const [precio, setPrecio] = useState(50);
  
  const demandaParams = { a: 100, b: 1 };
  const ofertaParams = { c: 10, d: 0.8 };

  const puntoEquilibrio = useMemo(() => {
    const { a, b } = demandaParams;
    const { c, d } = ofertaParams;
    const pEq = (a - c) / (b + d);
    const qEq = a - b * pEq;
    return { pEq, qEq };
  }, []);

  const datosCurvas = useMemo(() => {
    const puntos = [];
    const { a, b } = demandaParams;
    const { c, d } = ofertaParams;
    
    for (let q = 0; q <= 100; q += 5) {
      const pDemanda = (a - q) / b;
      const pOferta = q > 0 ? (q - c) / d : 0;
      puntos.push({ q, pDemanda: Math.max(0, pDemanda), pOferta: Math.max(0, pOferta) });
    }
    
    return puntos;
  }, []);

  const excedentes = useMemo(() => {
    const { a } = demandaParams;
    const { c } = ofertaParams;
    
    const qAlPrecio = Math.max(0, a - demandaParams.b * precio);
    const qOfrecida = Math.max(0, c + ofertaParams.d * precio);
    
    const excedenteConsumidor = 0.5 * qAlPrecio * (a - precio);
    const excedenteProductor = 0.5 * qOfrecida * (precio - c);
    
    return {
      ec: excedenteConsumidor,
      ep: excedenteProductor,
      total: excedenteConsumidor + excedenteProductor,
      qAlPrecio,
      qOfrecida,
    };
  }, [precio]);

  const excedentesEquilibrio = useMemo(() => {
    const { pEq, qEq } = puntoEquilibrio;
    const { a } = demandaParams;
    const { c } = ofertaParams;
    
    const ec = 0.5 * qEq * (a - pEq);
    const ep = 0.5 * qEq * (pEq - c);
    
    return { ec, ep, total: ec + ep };
  }, [puntoEquilibrio]);

  const maxP = 100;
  const maxQ = 100;
  const escalaX = 350 / maxQ;
  const escalaY = 180 / maxP;

  const handleCompletar = () => {
    if (onComplete) {
      onComplete(100);
    }
    return 100;
  };

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader
          title="Visualizador de Excedentes"
          subtitle="Ajusta el precio para ver cómo cambian los excedentes del consumidor y productor"
        />

        <div className="mb-6 p-4 bg-blue-50 rounded-lg">
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Precio de Mercado (P)
          </label>
          <div className="flex items-center gap-4">
            <Input
              type="range"
              min="20"
              max="90"
              value={precio}
              onChange={(e) => setPrecio(parseFloat(e.target.value))}
              className="flex-1"
            />
            <span className="text-2xl font-bold text-primary min-w-[80px]">${precio}</span>
          </div>
          <div className="flex justify-between text-xs text-gray-500 mt-1">
            <span>$20</span>
            <span>Precio de equilibrio: ${puntoEquilibrio.pEq.toFixed(1)}</span>
            <span>$90</span>
          </div>
        </div>

        <div className="relative h-80 bg-gray-50 rounded-lg p-4 overflow-hidden">
          <svg className="w-full h-full" viewBox="0 0 400 220" preserveAspectRatio="xMidYMid meet">
            <line x1="50" y1="200" x2="380" y2="200" stroke="#374151" strokeWidth="2" />
            <line x1="50" y1="200" x2="50" y2="20" stroke="#374151" strokeWidth="2" />
            
            <text x="215" y="215" textAnchor="middle" className="text-sm fill-gray-700 font-medium">Cantidad (Q)</text>
            <text x="15" y="110" textAnchor="middle" className="text-sm fill-gray-700 font-medium" transform="rotate(-90 15 110)">Precio (P)</text>
            
            {[0, 25, 50, 75, 100].map((q) => (
              <g key={q}>
                <line
                  x1={50 + q * escalaX}
                  y1="200"
                  x2={50 + q * escalaX}
                  y2="205"
                  stroke="#374151"
                  strokeWidth="1"
                />
                <text
                  x={50 + q * escalaX}
                  y="215"
                  textAnchor="middle"
                  className="text-xs fill-gray-500"
                >
                  {q}
                </text>
              </g>
            ))}
            
            {[0, 25, 50, 75, 100].map((p) => (
              <g key={p}>
                <line
                  x1="45"
                  y1={200 - p * escalaY}
                  x2="50"
                  y2={200 - p * escalaY}
                  stroke="#374151"
                  strokeWidth="1"
                />
                <text
                  x="40"
                  y={200 - p * escalaY + 4}
                  textAnchor="end"
                  className="text-xs fill-gray-500"
                >
                  {p}
                </text>
              </g>
            ))}

            <line
              x1="50"
              y1={200 - precio * escalaY}
              x2="380"
              y2={200 - precio * escalaY}
              stroke="#7c3aed"
              strokeWidth="2"
              strokeDasharray="5,5"
              opacity="0.7"
            />
            <text x="385" y={200 - precio * escalaY + 4} className="text-xs fill-purple-600 font-medium">
              P = {precio}
            </text>

            {precio > puntoEquilibrio.pEq && (
              <polygon
                points={`
                  50,${200 - precio * escalaY}
                  ${50 + excedentes.qAlPrecio * escalaX},${200 - precio * escalaY}
                  ${50 + excedentes.qAlPrecio * escalaX},${200 - ((100 - excedentes.qAlPrecio)) * escalaY}
                `}
                fill="rgba(37, 99, 235, 0.3)"
                stroke="#2563eb"
                strokeWidth="1"
              />
            )}

            {precio < puntoEquilibrio.pEq && (
              <polygon
                points={`
                  50,${200 - 12.5 * escalaY}
                  ${50 + excedentes.qOfrecida * escalaX},${200 - precio * escalaY}
                  50,${200 - precio * escalaY}
                `}
                fill="rgba(22, 163, 74, 0.3)"
                stroke="#16a34a"
                strokeWidth="1"
              />
            )}

            {Math.abs(precio - puntoEquilibrio.pEq) < 2 && (
              <>
                <polygon
                  points={`
                    50,${200 - puntoEquilibrio.pEq * escalaY}
                    ${50 + puntoEquilibrio.qEq * escalaX},${200 - puntoEquilibrio.pEq * escalaY}
                    ${50 + puntoEquilibrio.qEq * escalaX},${200 - 100 * escalaY}
                  `}
                  fill="rgba(37, 99, 235, 0.3)"
                  stroke="#2563eb"
                  strokeWidth="1"
                />
                <polygon
                  points={`
                    50,${200 - 12.5 * escalaY}
                    ${50 + puntoEquilibrio.qEq * escalaX},${200 - puntoEquilibrio.pEq * escalaY}
                    50,${200 - puntoEquilibrio.pEq * escalaY}
                  `}
                  fill="rgba(22, 163, 74, 0.3)"
                  stroke="#16a34a"
                  strokeWidth="1"
                />
              </>
            )}

            <polyline
              fill="none"
              stroke="#2563eb"
              strokeWidth="3"
              points={datosCurvas.map(d => `${50 + d.q * escalaX},${200 - d.pDemanda * escalaY}`).join(' ')}
            />
            
            <polyline
              fill="none"
              stroke="#16a34a"
              strokeWidth="3"
              points={datosCurvas.filter(d => d.pOferta >= 0).map(d => `${50 + d.q * escalaX},${200 - d.pOferta * escalaY}`).join(' ')}
            />

            <circle
              cx={50 + puntoEquilibrio.qEq * escalaX}
              cy={200 - puntoEquilibrio.pEq * escalaY}
              r="6"
              fill="#dc2626"
              stroke="white"
              strokeWidth="2"
            />
            <text
              x={50 + puntoEquilibrio.qEq * escalaX}
              y={200 - puntoEquilibrio.pEq * escalaY - 12}
              textAnchor="middle"
              className="text-xs fill-red-600 font-bold"
            >
              E
            </text>

            <g transform="translate(320, 40)">
              <line x1="0" y1="0" x2="25" y2="0" stroke="#2563eb" strokeWidth="3" />
              <text x="30" y="5" className="text-xs fill-gray-700">Demanda</text>
              <line x1="0" y1="15" x2="25" y2="15" stroke="#16a34a" strokeWidth="3" />
              <text x="30" y="20" className="text-xs fill-gray-700">Oferta</text>
              <rect x="0" y="30" width="15" height="15" fill="rgba(37, 99, 235, 0.3)" stroke="#2563eb" />
              <text x="20" y="42" className="text-xs fill-gray-700">EC</text>
              <rect x="0" y="50" width="15" height="15" fill="rgba(22, 163, 74, 0.3)" stroke="#16a34a" />
              <text x="20" y="62" className="text-xs fill-gray-700">EP</text>
            </g>
          </svg>
        </div>
      </Card>

      <div className="grid md:grid-cols-3 gap-4">
        <Card className="bg-blue-50 border-blue-200">
          <div className="flex items-center gap-2 mb-2">
            <div className="w-4 h-4 bg-blue-500/30 border border-blue-500 rounded" />
            <h4 className="font-semibold text-blue-900">Excedente del Consumidor</h4>
          </div>
          <p className="text-3xl font-bold text-blue-700">${excedentes.ec.toFixed(0)}</p>
          <p className="text-sm text-blue-600 mt-1">
            Área bajo la curva de demanda y sobre el precio
          </p>
        </Card>

        <Card className="bg-green-50 border-green-200">
          <div className="flex items-center gap-2 mb-2">
            <div className="w-4 h-4 bg-green-500/30 border border-green-500 rounded" />
            <h4 className="font-semibold text-green-900">Excedente del Productor</h4>
          </div>
          <p className="text-3xl font-bold text-green-700">${excedentes.ep.toFixed(0)}</p>
          <p className="text-sm text-green-600 mt-1">
            Área sobre la curva de oferta y bajo el precio
          </p>
        </Card>

        <Card className="bg-purple-50 border-purple-200">
          <div className="flex items-center gap-2 mb-2">
            <TrendingUp className="w-5 h-5 text-purple-600" />
            <h4 className="font-semibold text-purple-900">Excedente Total</h4>
          </div>
          <p className="text-3xl font-bold text-purple-700">${excedentes.total.toFixed(0)}</p>
          <p className="text-sm text-purple-600 mt-1">
            EC + EP = Bienestar social total
          </p>
        </Card>
      </div>

      <Card className="bg-yellow-50 border-yellow-200">
        <div className="flex items-start gap-3">
          <Info className="w-5 h-5 text-yellow-600 mt-0.5" />
          <div>
            <h4 className="font-semibold text-yellow-900 mb-2">En el Equilibrio de Mercado:</h4>
            <div className="grid md:grid-cols-3 gap-4 text-sm">
              <div>
                <span className="text-yellow-800">Precio: </span>
                <span className="font-bold">${puntoEquilibrio.pEq.toFixed(1)}</span>
              </div>
              <div>
                <span className="text-yellow-800">Cantidad: </span>
                <span className="font-bold">{puntoEquilibrio.qEq.toFixed(1)}</span>
              </div>
              <div>
                <span className="text-yellow-800">Excedente Total: </span>
                <span className="font-bold">${excedentesEquilibrio.total.toFixed(0)}</span>
              </div>
            </div>
            <p className="mt-3 text-yellow-800 text-sm">
              El equilibrio de mercado maximiza el bienestar social (excedente total). 
              Cualquier desviación del precio de equilibrio genera pérdida de eficiencia.
            </p>
          </div>
        </div>
      </Card>

      <div className="flex justify-end">
        <Button onClick={handleCompletar} size="lg">
          <CheckCircle className="w-5 h-5 mr-2" />
          Marcar como Completado
        </Button>
      </div>
    </div>
  );
}

export default VisualizadorExcedentes;
