'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinners';
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select';
import { RiSparklingLine, RiUserStarLine } from '@remixicon/react';
import { useGenerateLookalikes } from '../../hooks';
import { MatchScoreBadge, EmptyState, LoadingSkeleton } from '../shared/ScoreBar';
import type { LookalikeList, SimilarityMode } from '../../types';

const MODES: { value: SimilarityMode; label: string; desc: string }[] = [
  { value: 'mixed', label: 'Mixed', desc: 'Balanced across all factors' },
  { value: 'audience', label: 'Audience', desc: 'Focus on follower size & geography' },
  { value: 'niche', label: 'Niche', desc: 'Focus on category & content type' },
  { value: 'engagement_profile', label: 'Engagement', desc: 'Focus on engagement patterns' },
];

export function LookalikeGenerator() {
  const [seedIds, setSeedIds] = useState('');
  const [mode, setMode] = useState<SimilarityMode>('mixed');
  const [platform, setPlatform] = useState('');
  const [country, setCountry] = useState('');
  const [limit, setLimit] = useState('20');
  const [result, setResult] = useState<LookalikeList | null>(null);

  const { mutateAsync: generate, isPending } = useGenerateLookalikes();

  const handleGenerate = async () => {
    const ids = seedIds.split(',').map(s => Number(s.trim())).filter(n => n > 0);
    if (ids.length === 0) return;
    const data: Parameters<typeof generate>[0] = { seed_creator_ids: ids, similarity_mode: mode };
    if (platform) data.platform = platform;
    if (country) data.country = country;
    if (limit) data.limit = Number(limit);
    const res = await generate(data);
    setResult(res);
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground">Lookalike Creator Discovery</h1>
        <p className="text-sm text-muted-foreground mt-1">Find creators similar to your top performers</p>
      </div>

      <Card>
        <CardHeader><CardTitle className="text-sm">Configuration</CardTitle></CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Seed Creator IDs *</Label>
            <Input placeholder="Enter comma-separated IDs, e.g. 123, 456, 789" value={seedIds} onChange={e => setSeedIds(e.target.value)} />
          </div>
          <div>
            <Label className="text-xs font-medium text-muted-foreground mb-2 block">Similarity Mode</Label>
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-2">
              {MODES.map(m => (
                <button
                  key={m.value}
                  onClick={() => setMode(m.value)}
                  className={`p-3 rounded-lg border text-left transition-colors ${mode === m.value ? 'border-primary bg-primary/5 ring-1 ring-primary' : 'hover:bg-muted/50'}`}
                >
                  <div className="text-sm font-medium">{m.label}</div>
                  <div className="text-xs text-muted-foreground mt-0.5">{m.desc}</div>
                </button>
              ))}
            </div>
          </div>
          <div className="grid grid-cols-3 gap-3">
            <div>
              <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Platform</Label>
              <Select value={platform || 'all'} onValueChange={v => setPlatform(v === 'all' ? '' : v)}>
                <SelectTrigger className="h-9"><SelectValue placeholder="All" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All</SelectItem>
                  <SelectItem value="instagram">Instagram</SelectItem>
                  <SelectItem value="snapchat">Snapchat</SelectItem>
                  <SelectItem value="tiktok">TikTok</SelectItem>
                  <SelectItem value="youtube">YouTube</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Country</Label>
              <Input className="h-9" placeholder="e.g. SA" value={country} onChange={e => setCountry(e.target.value)} />
            </div>
            <div>
              <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Max Results</Label>
              <Input className="h-9" type="number" min={1} max={100} value={limit} onChange={e => setLimit(e.target.value)} />
            </div>
          </div>
          <Button className="w-full" onClick={handleGenerate} disabled={isPending || !seedIds.trim()}>
            {isPending ? <Spinner className="size-4 animate-spin mr-2" /> : <RiSparklingLine className="size-4 mr-2" />}
            Find Lookalikes
          </Button>
        </CardContent>
      </Card>

      {isPending ? (
        <Card><CardContent className="py-8"><LoadingSkeleton rows={5} /></CardContent></Card>
      ) : result ? (
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold">{result.items_count} Similar Creators Found</h2>
            <Badge variant="info" appearance="outline" className="capitalize">{result.similarity_mode} mode</Badge>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {result.items.map(item => (
              <Card key={item.id} className="hover:shadow-md transition-shadow">
                <CardContent className="pt-5">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-center gap-2">
                      <div className="size-10 rounded-full bg-primary/10 flex items-center justify-center">
                        <RiUserStarLine className="size-5 text-primary" />
                      </div>
                      <div>
                        <div className="font-medium text-sm">@{item.influencer.username}</div>
                        <div className="text-xs text-muted-foreground capitalize">{item.influencer.social_network} • {item.influencer.category}</div>
                      </div>
                    </div>
                    <MatchScoreBadge score={item.similarity_score} />
                  </div>
                  <div className="grid grid-cols-2 gap-2 text-center mb-3">
                    <div className="p-2 rounded bg-muted/50">
                      <div className="text-sm font-bold tabular-nums">{item.influencer.subscribers?.toLocaleString()}</div>
                      <div className="text-[10px] text-muted-foreground">Followers</div>
                    </div>
                    <div className="p-2 rounded bg-muted/50">
                      <div className="text-sm font-bold tabular-nums">{item.influencer.engagement_rate}%</div>
                      <div className="text-[10px] text-muted-foreground">Engagement</div>
                    </div>
                  </div>
                  <p className="text-xs text-muted-foreground">{item.similarity_reason}</p>
                  <Badge variant="mono" appearance="outline" className="text-[10px] mt-2 capitalize">{item.cluster_label} tier</Badge>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      ) : (
        <Card><CardContent><EmptyState title="No Lookalikes Yet" description="Enter seed creator IDs and choose a similarity mode to discover similar creators." /></CardContent></Card>
      )}
    </div>
  );
}
