'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 { Textarea } from '@/components/ui/textarea';
import { Spinner } from '@/components/ui/spinners';
import { RiSparklingLine, RiRefreshLine, RiShieldCheckLine, RiAlertLine } from '@remixicon/react';
import { useGenerateMatchReasoning, useRegenerateMatchReasoning } from '../../hooks';
import { ScoreBar, SectionCard, EmptyState, LoadingSkeleton } from '../shared/ScoreBar';
import type { MatchReasoning } from '../../types';

export function MatchReasoningPanel() {
  const [influencerId, setInfluencerId] = useState('');
  const [campaignContext, setCampaignContext] = useState({ name: '', objective: '', budget: '', platforms: '', target_audience: '' });
  const [result, setResult] = useState<MatchReasoning | null>(null);

  const { mutateAsync: generate, isPending } = useGenerateMatchReasoning();
  const { mutateAsync: regenerate, isPending: isRegenerating } = useRegenerateMatchReasoning();

  const handleGenerate = async () => {
    if (!influencerId) return;
    const data: { influencer_id: number; campaign_context?: Record<string, unknown> } = { influencer_id: Number(influencerId) };
    const ctx: Record<string, unknown> = {};
    if (campaignContext.name) ctx.name = campaignContext.name;
    if (campaignContext.objective) ctx.objective = campaignContext.objective;
    if (campaignContext.budget) ctx.budget = Number(campaignContext.budget);
    if (campaignContext.platforms) ctx.platforms = campaignContext.platforms.split(',').map(s => s.trim());
    if (campaignContext.target_audience) ctx.target_audience = campaignContext.target_audience;
    if (Object.keys(ctx).length > 0) data.campaign_context = ctx;
    const res = await generate(data);
    setResult(res);
  };

  const handleRegenerate = async () => {
    if (!result) return;
    const res = await regenerate(result.id);
    setResult(res);
  };

  const reasoning = result?.reasoning_output;

  const verdictColor = (v: string) => {
    const lower = v.toLowerCase();
    if (lower.includes('strong') || lower.includes('excellent')) return 'success';
    if (lower.includes('moderate') || lower.includes('good')) return 'warning';
    return 'destructive';
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground">Creator Match Reasoning</h1>
        <p className="text-sm text-muted-foreground mt-1">Get AI-powered analysis of creator-campaign fit</p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-5 gap-6">
        <div className="lg:col-span-2 space-y-4">
          <Card>
            <CardHeader><CardTitle className="text-sm">Evaluation Input</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Creator / Influencer ID *</Label>
                <Input type="number" placeholder="Enter influencer ID" value={influencerId} onChange={e => setInfluencerId(e.target.value)} />
              </div>
              <div>
                <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Campaign Name</Label>
                <Input placeholder="e.g. Summer Fashion Launch" value={campaignContext.name} onChange={e => setCampaignContext({ ...campaignContext, name: e.target.value })} />
              </div>
              <div>
                <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Objective</Label>
                <Input placeholder="e.g. Brand awareness" value={campaignContext.objective} onChange={e => setCampaignContext({ ...campaignContext, objective: e.target.value })} />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Budget</Label>
                  <Input type="number" placeholder="e.g. 50000" value={campaignContext.budget} onChange={e => setCampaignContext({ ...campaignContext, budget: e.target.value })} />
                </div>
                <div>
                  <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Platforms</Label>
                  <Input placeholder="instagram, snapchat" value={campaignContext.platforms} onChange={e => setCampaignContext({ ...campaignContext, platforms: e.target.value })} />
                </div>
              </div>
              <div>
                <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Target Audience</Label>
                <Textarea placeholder="Describe target audience" value={campaignContext.target_audience} onChange={e => setCampaignContext({ ...campaignContext, target_audience: e.target.value })} rows={2} />
              </div>
              <Button className="w-full" onClick={handleGenerate} disabled={isPending || !influencerId}>
                {isPending ? <Spinner className="size-4 animate-spin mr-2" /> : <RiSparklingLine className="size-4 mr-2" />}
                Analyze Match
              </Button>
            </CardContent>
          </Card>
        </div>

        <div className="lg:col-span-3 space-y-4">
          {isPending || isRegenerating ? (
            <Card><CardContent className="py-8"><LoadingSkeleton rows={5} /></CardContent></Card>
          ) : reasoning ? (
            <>
              <div className="flex items-center justify-between">
                <Badge variant={verdictColor(reasoning.overall_verdict)} className="text-sm px-3 py-1">
                  {reasoning.overall_verdict}
                </Badge>
                <Button variant="outline" size="sm" onClick={handleRegenerate}>
                  <RiRefreshLine className="size-4 mr-1.5" />Regenerate
                </Button>
              </div>

              <SectionCard title="Match Narrative">
                <p className="text-sm text-foreground leading-relaxed">{reasoning.match_narrative}</p>
              </SectionCard>

              <SectionCard title="Fit Scores">
                <div className="space-y-3">
                  <ScoreBar label="Audience Fit" score={reasoning.audience_fit_score} />
                  <ScoreBar label="Geography Fit" score={reasoning.geography_fit_score} />
                  <ScoreBar label="Content Fit" score={reasoning.content_fit_score} />
                  <ScoreBar label="Platform Fit" score={reasoning.platform_fit_score} />
                  <ScoreBar label="Budget Fit" score={reasoning.estimated_budget_fit_score} />
                </div>
              </SectionCard>

              {reasoning.strengths.length > 0 && (
                <SectionCard title="Strengths">
                  <div className="space-y-2">
                    {reasoning.strengths.map((s, i) => (
                      <div key={i} className="flex items-start gap-2 text-sm">
                        <RiShieldCheckLine className="size-4 text-emerald-500 shrink-0 mt-0.5" />
                        <span>{s}</span>
                      </div>
                    ))}
                  </div>
                </SectionCard>
              )}

              {reasoning.risks.length > 0 && (
                <SectionCard title="Risks">
                  <div className="space-y-2">
                    {reasoning.risks.map((r, i) => (
                      <div key={i} className="flex items-start gap-2 text-sm">
                        <RiAlertLine className="size-4 text-amber-500 shrink-0 mt-0.5" />
                        <span>{r}</span>
                      </div>
                    ))}
                  </div>
                </SectionCard>
              )}

              {reasoning.recommendations.length > 0 && (
                <SectionCard title="Recommendations">
                  <div className="space-y-2">
                    {reasoning.recommendations.map((r, i) => (
                      <div key={i} className="flex items-start gap-2 text-sm">
                        <span className="size-5 rounded-full bg-blue-100 text-blue-700 flex items-center justify-center text-xs font-bold shrink-0">{i + 1}</span>
                        <span>{r}</span>
                      </div>
                    ))}
                  </div>
                </SectionCard>
              )}
            </>
          ) : (
            <Card><CardContent><EmptyState title="No Analysis Yet" description="Enter a creator ID and campaign context to generate match reasoning." /></CardContent></Card>
          )}
        </div>
      </div>
    </div>
  );
}
