'use client';

import { useState } from 'react';
import { ColorPicker } from '@/components/color/ColorPicker';
import { ColorDisplay } from '@/components/color/ColorDisplay';
import { Button } from '@/components/ui/button';
import { useTextColor } from '@/lib/api/queries';
import { Loader2, Palette, Plus, X, CheckCircle2, XCircle } from 'lucide-react';
import { toast } from 'sonner';

export default function TextColorPage() {
  const [backgrounds, setBackgrounds] = useState<string[]>(['#ff0099']);
  const [results, setResults] = useState<
    Array<{
      background: string;
      textcolor: string;
      contrast_ratio: number;
      wcag_aa: boolean;
      wcag_aaa: boolean;
    }>
  >([]);

  const textColorMutation = useTextColor();

  const handleOptimize = async () => {
    try {
      const result = await textColorMutation.mutateAsync({
        backgrounds,
      });
      setResults(result.colors);
      toast.success(`Optimized text colors for ${result.colors.length} background(s)`);
    } catch (error) {
      toast.error('Failed to optimize text colors');
      console.error(error);
    }
  };

  const addBackground = () => {
    if (backgrounds.length < 10) {
      setBackgrounds([...backgrounds, '#000000']);
    }
  };

  const removeBackground = (index: number) => {
    if (backgrounds.length > 1) {
      setBackgrounds(backgrounds.filter((_, i) => i !== index));
    }
  };

  const updateBackground = (index: number, color: string) => {
    const newBackgrounds = [...backgrounds];
    newBackgrounds[index] = color;
    setBackgrounds(newBackgrounds);
  };

  return (
    <div className="min-h-screen p-8">
      <div className="max-w-7xl mx-auto space-y-8">
        <div>
          <h1 className="text-4xl font-bold mb-2">Text Color Optimizer</h1>
          <p className="text-muted-foreground">
            Automatically find the best text color (black or white) for any background color
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* Input */}
          <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-xl font-semibold">Background Colors</h2>
                <Button
                  onClick={addBackground}
                  disabled={backgrounds.length >= 10}
                  variant="outline"
                  size="sm"
                >
                  <Plus className="h-4 w-4 mr-2" />
                  Add
                </Button>
              </div>

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

              <Button
                onClick={handleOptimize}
                disabled={textColorMutation.isPending || backgrounds.length === 0}
                className="w-full mt-4"
              >
                {textColorMutation.isPending ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Optimizing...
                  </>
                ) : (
                  <>
                    <Palette className="mr-2 h-4 w-4" />
                    Optimize Text Colors
                  </>
                )}
              </Button>
            </div>

            <div className="p-6 border rounded-lg bg-card bg-blue-50 dark:bg-blue-950/20">
              <h3 className="font-semibold mb-2">How it works</h3>
              <p className="text-sm text-muted-foreground">
                This tool analyzes each background color and automatically selects either black
                or white text to ensure maximum readability. The algorithm guarantees WCAG AA
                compliance (4.5:1 contrast ratio) for normal text.
              </p>
            </div>
          </div>

          {/* Results */}
          <div className="space-y-6">
            {results.length > 0 ? (
              <>
                <div className="p-6 border rounded-lg bg-card">
                  <h2 className="text-xl font-semibold mb-4">Optimized Results</h2>
                  <div className="space-y-4">
                    {results.map((result, index) => (
                      <div
                        key={index}
                        className="p-4 border rounded-lg"
                        style={{ backgroundColor: result.background }}
                      >
                        <div className="flex items-center justify-between mb-3">
                          <div className="flex items-center gap-3">
                            <ColorDisplay color={result.background} size="sm" />
                            <code className="text-sm font-mono text-inherit">
                              {result.background}
                            </code>
                          </div>
                        </div>

                        <div
                          className="p-4 rounded border-2"
                          style={{
                            backgroundColor: result.background,
                            color: result.textcolor,
                            borderColor: result.textcolor,
                          }}
                        >
                          <p className="font-semibold mb-2" style={{ color: result.textcolor }}>
                            Sample Text Preview
                          </p>
                          <p className="text-sm" style={{ color: result.textcolor }}>
                            The quick brown fox jumps over the lazy dog. This is how your text
                            will look on this background color.
                          </p>
                        </div>

                        <div className="mt-3 grid grid-cols-2 gap-3 text-sm">
                          <div>
                            <span className="text-muted-foreground">Text Color: </span>
                            <code className="font-mono">{result.textcolor}</code>
                          </div>
                          <div>
                            <span className="text-muted-foreground">Contrast: </span>
                            <span className="font-medium">
                              {result.contrast_ratio.toFixed(2)}:1
                            </span>
                          </div>
                          <div className="flex items-center gap-2">
                            {result.wcag_aa ? (
                              <CheckCircle2 className="h-4 w-4 text-green-500" />
                            ) : (
                              <XCircle className="h-4 w-4 text-red-500" />
                            )}
                            <span className={result.wcag_aa ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'}>
                              WCAG AA
                            </span>
                          </div>
                          <div className="flex items-center gap-2">
                            {result.wcag_aaa ? (
                              <CheckCircle2 className="h-4 w-4 text-green-500" />
                            ) : (
                              <XCircle className="h-4 w-4 text-yellow-500" />
                            )}
                            <span className={result.wcag_aaa ? 'text-green-600 dark:text-green-400' : 'text-yellow-600 dark:text-yellow-400'}>
                              WCAG AAA
                            </span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </>
            ) : (
              <div className="p-12 border rounded-lg bg-card text-center text-muted-foreground">
                <Palette className="h-12 w-12 mx-auto mb-4 opacity-50" />
                <p>Add background colors and click Optimize to see results</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
