'use client';

import { useState } from 'react';
import { ColorPicker } from '@/components/pastel/color/ColorPicker';
import { ColorDisplay } from '@/components/pastel/color/ColorDisplay';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useSimulateColorBlindness } from '@/lib/pastel/api/queries';
import { Loader2, Eye, Plus, X } from 'lucide-react';
import { toast } from 'sonner';

type ColorBlindnessType = 'protanopia' | 'deuteranopia' | 'tritanopia';

export default function ColorBlindPage() {
  const [colors, setColors] = useState<string[]>(['#ff0099']);
  const [blindnessType, setBlindnessType] = useState<ColorBlindnessType>('protanopia');
  const [simulations, setSimulations] = useState<
    Array<{ input: string; output: string; difference_percentage: number }>
  >([]);

  const simulateMutation = useSimulateColorBlindness();

  const handleSimulate = async () => {
    try {
      const result = await simulateMutation.mutateAsync({
        colors,
        type: blindnessType,
      });
      setSimulations(result.colors);
      toast.success(`Simulated ${blindnessType}`);
    } catch (error) {
      toast.error('Failed to simulate color blindness');
      console.error(error);
    }
  };

  const addColor = () => {
    if (colors.length < 10) {
      setColors([...colors, '#000000']);
    }
  };

  const removeColor = (index: number) => {
    if (colors.length > 1) {
      setColors(colors.filter((_, i) => i !== index));
    }
  };

  const updateColor = (index: number, color: string) => {
    const newColors = [...colors];
    newColors[index] = color;
    setColors(newColors);
  };

  const typeDescriptions: Record<ColorBlindnessType, string> = {
    protanopia: 'Red-blind (affects ~1% of males)',
    deuteranopia: 'Green-blind (affects ~1% of males)',
    tritanopia: 'Blue-blind (rare, affects ~0.001%)',
  };

  return (
    <div className="min-h-screen py-12">
      <div className="max-w-7xl mx-auto px-8 space-y-8">
        <div>
          <h1 className="text-4xl font-bold mb-2">Color Blindness Simulator</h1>
          <p className="text-muted-foreground">
            Simulate how colors appear with different types of color blindness
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* Controls */}
          <div className="space-y-6">
            <div className="p-6 border rounded-lg bg-card">
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-sm font-medium">Colors to Test</h2>
                <Button
                  onClick={addColor}
                  variant="outline"
                  size="sm"
                  disabled={colors.length >= 10}
                >
                  <Plus className="h-4 w-4 mr-2" />
                  Add Color
                </Button>
              </div>

              <div className="space-y-4">
                {colors.map((color, index) => (
                  <div key={index} className="flex items-start gap-3">
                    <div className="flex-1">
                      <ColorPicker
                        color={color}
                        onChange={(newColor) => updateColor(index, newColor)}
                      />
                    </div>
                    {colors.length > 1 && (
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => removeColor(index)}
                        className="mt-8"
                      >
                        <X className="h-4 w-4" />
                      </Button>
                    )}
                  </div>
                ))}
              </div>
            </div>

            <div className="p-6 border rounded-lg bg-card">
              <h2 className="text-sm font-medium mb-4">Blindness Type</h2>
              <div className="space-y-4">
                <Select
                  value={blindnessType}
                  onValueChange={(value) => setBlindnessType(value as ColorBlindnessType)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select type" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="protanopia">Protanopia (Red-blind)</SelectItem>
                    <SelectItem value="deuteranopia">Deuteranopia (Green-blind)</SelectItem>
                    <SelectItem value="tritanopia">Tritanopia (Blue-blind)</SelectItem>
                  </SelectContent>
                </Select>

                <p className="text-sm text-muted-foreground">
                  {typeDescriptions[blindnessType]}
                </p>

                <Button
                  onClick={handleSimulate}
                  disabled={simulateMutation.isPending || colors.length === 0}
                  className="w-full"
                >
                  {simulateMutation.isPending ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Simulating..
                    </>
                  ) : (
                    <>
                      <Eye className="mr-2 h-4 w-4" />
                      Simulate
                    </>
                  )}
                </Button>
              </div>
            </div>
          </div>

          {/* Results */}
          <div className="space-y-6">
            {simulations.length > 0 ? (
              <>
                <div className="p-6 border rounded-lg bg-card">
                  <h2 className="text-sm font-medium mb-4">Simulation Results</h2>
                  <p className="text-sm text-muted-foreground mb-6">
                    Compare original colors (left) with how they appear to people with{' '}
                    {blindnessType} (right)
                  </p>

                  <div className="space-y-4">
                    {simulations.map((sim, index) => (
                      <div
                        key={index}
                        className="grid grid-cols-2 gap-4 p-4 bg-muted/50 rounded-lg"
                      >
                        <div className="space-y-2">
                          <p className="text-xs font-medium text-muted-foreground">
                            Original
                          </p>
                          <div className="flex items-center gap-3">
                            <ColorDisplay color={sim.input} size="md" />
                            <code className="text-sm font-mono">{sim.input}</code>
                          </div>
                        </div>

                        <div className="space-y-2">
                          <p className="text-xs font-medium text-muted-foreground">
                            As Seen ({sim.difference_percentage.toFixed(1)}% difference)
                          </p>
                          <div className="flex items-center gap-3">
                            <ColorDisplay color={sim.output} size="md" />
                            <code className="text-sm font-mono">{sim.output}</code>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="p-6 border rounded-lg bg-card bg-blue-50 dark:bg-blue-950/20">
                  <h3 className="font-semibold mb-2 flex items-center gap-2">
                    <Eye className="h-5 w-5" />
                    Accessibility Tip
                  </h3>
                  <p className="text-sm text-muted-foreground">
                    Ensure important information isn&apos;t conveyed by color alone. Use text
                    labels, patterns, or icons to make your design accessible to everyone
                  </p>
                </div>
              </>
            ) : (
              <div className="p-12 border rounded-lg bg-card text-center text-muted-foreground">
                <Eye className="h-12 w-12 mx-auto mb-4 opacity-50" />
                <p>Add colors and click Simulate to see how they appear</p>
                <p className="text-sm mt-2">with different types of color blindness</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
