import { MessageSquare, Users, X } from 'lucide-react';

import { useState } from 'react';

import { useForm, usePage } from '@inertiajs/react';

import { Button } from '@/Components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/Components/ui/select';
import { Textarea } from '@/Components/ui/textarea';
import { trackEvent } from '@/lib/analytics';
import { FEEDBACK_SUBMITTED } from '@/lib/event-catalog';
import { cn } from '@/lib/utils';
import type { PageProps } from '@/types';

const ALL_IMPACT_CHIPS = [
  { value: 'content_quality', label: 'Content quality' },
  { value: 'speed_performance', label: 'Speed / performance' },
  { value: 'feature_gaps', label: 'Feature gaps' },
  { value: 'ai_draft_quality', label: 'AI draft quality' },
  { value: 'content_score', label: 'Content score' },
  { value: 'analysis_accuracy', label: 'Analysis accuracy' },
  { value: 'gsc_data', label: 'GSC data' },
  { value: 'recommendation_relevance', label: 'Recommendation relevance' },
] as const;

type ImpactArea = (typeof ALL_IMPACT_CHIPS)[number]['value'];

const IMPACT_CHIP_MAP = Object.fromEntries(
  ALL_IMPACT_CHIPS.map((c) => [c.value, c]),
) as Record<ImpactArea, { value: ImpactArea; label: string }>;

const DEFAULT_IMPACT: ImpactArea[] = ['content_quality', 'speed_performance', 'feature_gaps'];

const ROUTE_TO_IMPACT_MAP: Array<{ prefix: string; chips: ImpactArea[] }> = [
  { prefix: 'ContentEditor', chips: ['ai_draft_quality', 'content_score'] },
  { prefix: 'Analyze', chips: ['analysis_accuracy', 'gsc_data'] },
  { prefix: 'Recommendations', chips: ['recommendation_relevance', 'ai_draft_quality'] },
];

function getContextualChips(component: string): ImpactArea[] {
  for (const { prefix, chips } of ROUTE_TO_IMPACT_MAP) {
    if (component.startsWith(prefix)) {
      return chips;
    }
  }
  return DEFAULT_IMPACT;
}

interface FeedbackForm {
  message: string;
  category: string;
  metadata: { impact_areas?: ImpactArea[] };
}

export function FeedbackWidget() {
  const page = usePage<PageProps>();
  const { community_url } = page.props;
  const contextualChips = getContextualChips(
    typeof page.component === 'string' ? page.component : '',
  );
  const [isOpen, setIsOpen] = useState(false);
  const [submitted, setSubmitted] = useState(false);

  const { data, setData, post, processing, reset, errors } = useForm<FeedbackForm>({
    message: '',
    category: 'general',
    metadata: {},
  });

  const selectedImpact: ImpactArea[] = data.metadata.impact_areas ?? [];

  const toggleImpact = (area: ImpactArea) => {
    const next = selectedImpact.includes(area)
      ? selectedImpact.filter((a) => a !== area)
      : [...selectedImpact, area];
    setData('metadata', next.length > 0 ? { impact_areas: next } : {});
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    post(route('feedback.store'), {
      onSuccess: () => {
        trackEvent(FEEDBACK_SUBMITTED, { category: data.category });
        setSubmitted(true);
        reset();
        setTimeout(() => {
          setIsOpen(false);
          setSubmitted(false);
        }, 2000);
      },
    });
  };

  if (!isOpen) {
    return (
      <button
        onClick={() => setIsOpen(true)}
        className="fixed bottom-20 right-4 z-50 flex h-10 w-10 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg transition-transform hover:scale-110"
        aria-label="Send feedback"
      >
        <MessageSquare className="h-5 w-5" />
      </button>
    );
  }

  return (
    <div className="fixed bottom-20 right-4 z-50 w-80 rounded-lg border bg-card p-4 shadow-xl">
      <div className="mb-3 flex items-center justify-between">
        <h3 className="text-sm font-semibold">Send Feedback</h3>
        <button
          onClick={() => setIsOpen(false)}
          className="text-muted-foreground hover:text-foreground"
          aria-label="Close feedback"
        >
          <X className="h-4 w-4" />
        </button>
      </div>

      {submitted ? (
        <div className="py-4 text-center">
          <p className="text-sm text-muted-foreground">Thank you for your feedback!</p>
          {community_url ? (
            <a
              href={community_url}
              target="_blank"
              rel="noopener noreferrer"
              className="mt-2 inline-flex items-center gap-1.5 text-xs text-primary hover:underline"
            >
              <Users className="h-3 w-3" />
              Join the community
            </a>
          ) : (
            <a
              href="mailto:feedback@rankwiz.ai"
              className="mt-2 inline-flex items-center gap-1.5 text-xs text-primary hover:underline"
            >
              Contact support
            </a>
          )}
        </div>
      ) : (
        <form onSubmit={handleSubmit} className="space-y-3">
          <Select value={data.category} onValueChange={(val) => setData('category', val)}>
            <SelectTrigger className="h-8 text-xs">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="general">General feedback</SelectItem>
              <SelectItem value="bug">Bug report</SelectItem>
              <SelectItem value="feature_request">Feature request</SelectItem>
            </SelectContent>
          </Select>

          <div>
            <p className="mb-1.5 text-xs text-muted-foreground">Impact area (optional)</p>
            <div className="flex flex-wrap gap-1.5">
              {contextualChips.map((value) => {
                const chip = IMPACT_CHIP_MAP[value];
                return (
                  <button
                    key={chip.value}
                    type="button"
                    onClick={() => toggleImpact(chip.value)}
                    className={cn(
                      'rounded-full border px-2.5 py-0.5 text-xs transition-colors',
                      selectedImpact.includes(chip.value)
                        ? 'border-primary bg-primary text-primary-foreground'
                        : 'border-border bg-background text-muted-foreground hover:border-primary hover:text-foreground',
                    )}
                  >
                    {chip.label}
                  </button>
                );
              })}
            </div>
          </div>

          <Textarea
            value={data.message}
            onChange={(e) => setData('message', e.target.value)}
            placeholder="Tell us what you think..."
            className="min-h-[80px] text-sm"
            maxLength={2000}
          />
          {errors.message && <p className="text-xs text-destructive">{errors.message}</p>}

          <Button
            type="submit"
            size="sm"
            className="w-full"
            disabled={processing || !data.message.trim()}
          >
            {processing ? 'Sending...' : 'Send'}
          </Button>

          {community_url ? (
            <a
              href={community_url}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center justify-center gap-1.5 text-xs text-muted-foreground hover:text-foreground"
            >
              <Users className="h-3 w-3" />
              Join the community
            </a>
          ) : (
            <a
              href="mailto:feedback@rankwiz.ai"
              className="flex items-center justify-center gap-1.5 text-xs text-muted-foreground hover:text-foreground"
            >
              Contact support
            </a>
          )}
        </form>
      )}
    </div>
  );
}
