'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 { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinners';
import { RiSparklingLine, RiArrowRightLine } from '@remixicon/react';
import { useParseBrief, useConvertBriefToFilters } from '../../hooks';
import { SectionCard, EmptyState, LoadingSkeleton } from '../shared/ScoreBar';
import type { BriefParse } from '../../types';

function ConfidenceBadge({ score }: { score: number }) {
  const color = score >= 0.8 ? 'success' : score >= 0.6 ? 'warning' : 'destructive';
  return (
    <Badge variant={color} appearance="outline" className="text-xs">
      {Math.round(score * 100)}% confidence
    </Badge>
  );
}

export function BriefParserPanel() {
  const [rawText, setRawText] = useState('');
  const [clientNotes, setClientNotes] = useState('');
  const [result, setResult] = useState<BriefParse | null>(null);

  const { mutateAsync: parse, isPending } = useParseBrief();
  const { mutateAsync: convertToFilters, isPending: isConverting } = useConvertBriefToFilters();

  const handleParse = async () => {
    if (!rawText.trim()) return;
    const data: { raw_brief_text: string; client_notes?: string } = { raw_brief_text: rawText };
    if (clientNotes.trim()) data.client_notes = clientNotes;
    const res = await parse(data);
    setResult(res);
  };

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

  const parsed = result?.parsed_output;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground">AI Brief Parser</h1>
        <p className="text-sm text-muted-foreground mt-1">Paste a raw campaign brief and let AI extract structured requirements</p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="space-y-4">
          <Card>
            <CardHeader><CardTitle className="text-sm">Raw Brief</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <Textarea
                placeholder="Paste your campaign brief here... e.g. 'We need 5-10 Saudi lifestyle influencers on Instagram and Snapchat to promote our summer collection. Budget 30-50K SAR, June 1 to July 15.'"
                value={rawText}
                onChange={e => setRawText(e.target.value)}
                rows={10}
                className="resize-none"
              />
              <div>
                <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Client Notes (Optional)</Label>
                <Input placeholder="Additional context about the brand..." value={clientNotes} onChange={e => setClientNotes(e.target.value)} />
              </div>
              <Button className="w-full" onClick={handleParse} disabled={isPending || rawText.trim().length < 10}>
                {isPending ? <Spinner className="size-4 animate-spin mr-2" /> : <RiSparklingLine className="size-4 mr-2" />}
                Parse Brief
              </Button>
            </CardContent>
          </Card>
        </div>

        <div className="space-y-4">
          {isPending ? (
            <Card><CardContent className="py-8"><LoadingSkeleton rows={4} /></CardContent></Card>
          ) : parsed ? (
            <>
              <div className="flex items-center justify-between">
                <ConfidenceBadge score={result!.confidence_score} />
                <Button variant="outline" size="sm" onClick={handleConvert} disabled={isConverting}>
                  {isConverting ? <Spinner className="size-4 animate-spin mr-1.5" /> : <RiArrowRightLine className="size-4 mr-1.5" />}
                  Convert to Search Filters
                </Button>
              </div>

              <SectionCard title="Campaign Overview">
                <div className="space-y-3 text-sm">
                  <div className="flex justify-between"><span className="text-muted-foreground">Campaign Name</span><span className="font-medium">{parsed.campaign_name}</span></div>
                  <div className="flex justify-between"><span className="text-muted-foreground">Objective</span><span className="font-medium">{parsed.objective}</span></div>
                  <div className="flex justify-between"><span className="text-muted-foreground">Platforms</span><div className="flex gap-1">{parsed.platforms.map(p => <Badge key={p} variant="info" appearance="outline" className="text-xs">{p}</Badge>)}</div></div>
                  <div className="flex justify-between"><span className="text-muted-foreground">Geographies</span><span className="font-medium">{parsed.geographies.join(', ')}</span></div>
                </div>
              </SectionCard>

              {parsed.budget && (
                <SectionCard title="Budget & Timeline">
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div className="p-3 rounded-lg bg-muted/50 text-center">
                      <div className="text-lg font-bold">{parsed.budget.range_min?.toLocaleString()} - {parsed.budget.range_max?.toLocaleString()}</div>
                      <div className="text-xs text-muted-foreground">{parsed.budget.currency}</div>
                    </div>
                    {parsed.timeline && (
                      <div className="p-3 rounded-lg bg-muted/50 text-center">
                        <div className="text-lg font-bold">{parsed.timeline.start_date}</div>
                        <div className="text-xs text-muted-foreground">to {parsed.timeline.end_date}</div>
                      </div>
                    )}
                  </div>
                </SectionCard>
              )}

              {parsed.creator_requirements && (
                <SectionCard title="Creator Requirements">
                  <div className="space-y-2 text-sm">
                    <div className="flex justify-between"><span className="text-muted-foreground">Count</span><span className="font-medium">{parsed.creator_requirements.count}</span></div>
                    <div className="flex justify-between"><span className="text-muted-foreground">Niche</span><span className="font-medium">{parsed.creator_requirements.niche}</span></div>
                    <div className="flex justify-between"><span className="text-muted-foreground">Min Followers</span><span className="font-medium">{parsed.creator_requirements.min_followers?.toLocaleString()}</span></div>
                    {parsed.creator_requirements.gender && <div className="flex justify-between"><span className="text-muted-foreground">Gender</span><span className="font-medium capitalize">{parsed.creator_requirements.gender}</span></div>}
                    {parsed.creator_requirements.tier && <div className="flex justify-between"><span className="text-muted-foreground">Tier</span><Badge variant="mono" appearance="outline" className="text-xs capitalize">{parsed.creator_requirements.tier}</Badge></div>}
                  </div>
                </SectionCard>
              )}

              {parsed.deliverables?.length > 0 && (
                <SectionCard title="Deliverables">
                  <div className="space-y-2">
                    {parsed.deliverables.map((d, i) => (
                      <div key={i} className="flex items-center justify-between text-sm p-2 rounded-lg bg-muted/30">
                        <span className="capitalize">{d.type.replace(/_/g, ' ')}</span>
                        <Badge variant="mono" appearance="outline" className="text-xs">{d.count}x</Badge>
                      </div>
                    ))}
                  </div>
                </SectionCard>
              )}

              {result?.search_filters && (
                <SectionCard title="Generated Search Filters">
                  <pre className="text-xs bg-muted/50 p-3 rounded-lg overflow-auto">{JSON.stringify(result.search_filters, null, 2)}</pre>
                </SectionCard>
              )}
            </>
          ) : (
            <Card>
              <CardContent>
                <EmptyState title="No Brief Parsed" description="Paste a campaign brief on the left to extract structured data." />
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}
