'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Spinner } from '@/components/ui/spinners';
import { RiSparklingLine, RiRefreshLine, RiHistoryLine } from '@remixicon/react';
import { useGenerateStrategy, useStrategyHistory, useRegenerateStrategy } from '../../hooks';
import { SectionCard, EmptyState, LoadingSkeleton } from '../shared/ScoreBar';
import type { StrategyInputs, StrategyRun } from '../../types';

const PLATFORM_OPTIONS = ['instagram', 'snapchat', 'tiktok', 'youtube', 'twitter'];
const COUNTRY_OPTIONS = [
  { code: 'SA', name: 'Saudi Arabia' }, { code: 'AE', name: 'UAE' },
  { code: 'KW', name: 'Kuwait' }, { code: 'BH', name: 'Bahrain' },
  { code: 'QA', name: 'Qatar' }, { code: 'OM', name: 'Oman' },
  { code: 'EG', name: 'Egypt' }, { code: 'JO', name: 'Jordan' },
];

export function StrategistPanel() {
  const [showHistory, setShowHistory] = useState(false);
  const [activeResult, setActiveResult] = useState<StrategyRun | null>(null);
  const [form, setForm] = useState<StrategyInputs>({
    brand_name: '', campaign_goal: '', target_audience: '',
    target_countries: [], target_platforms: [], budget_range: '',
    timeline: '', brand_tone: '', notes: '',
  });

  const { mutateAsync: generate, isPending } = useGenerateStrategy();
  const { mutateAsync: regenerate, isPending: isRegenerating } = useRegenerateStrategy();
  const { data: historyData } = useStrategyHistory();

  const toggleArrayItem = (key: 'target_countries' | 'target_platforms', value: string) => {
    setForm(prev => {
      const arr = prev[key] ?? [];
      return { ...prev, [key]: arr.includes(value) ? arr.filter(v => v !== value) : [...arr, value] };
    });
  };

  const handleGenerate = async () => {
    const cleaned: StrategyInputs = {};
    if (form.brand_name) cleaned.brand_name = form.brand_name;
    if (form.campaign_goal) cleaned.campaign_goal = form.campaign_goal;
    if (form.target_audience) cleaned.target_audience = form.target_audience;
    if (form.target_countries?.length) cleaned.target_countries = form.target_countries;
    if (form.target_platforms?.length) cleaned.target_platforms = form.target_platforms;
    if (form.budget_range) cleaned.budget_range = form.budget_range;
    if (form.timeline) cleaned.timeline = form.timeline;
    if (form.brand_tone) cleaned.brand_tone = form.brand_tone;
    if (form.notes) cleaned.notes = form.notes;
    const result = await generate(cleaned);
    setActiveResult(result);
  };

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

  const history = (historyData as { data?: StrategyRun[] })?.data ?? (Array.isArray(historyData) ? historyData : []);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">AI Campaign Strategist</h1>
          <p className="text-sm text-muted-foreground mt-1">Generate comprehensive campaign strategies powered by AI</p>
        </div>
        <Button variant="outline" size="sm" onClick={() => setShowHistory(!showHistory)}>
          <RiHistoryLine className="size-4 mr-1.5" />
          History
        </Button>
      </div>

      {showHistory && history.length > 0 && (
        <Card>
          <CardHeader><CardTitle className="text-sm">Previous Strategies</CardTitle></CardHeader>
          <CardContent className="space-y-2">
            {history.map((run: StrategyRun) => (
              <button
                key={run.id}
                className="w-full text-left p-3 rounded-lg border hover:bg-muted/50 transition-colors"
                onClick={() => { setActiveResult(run); setShowHistory(false); }}
              >
                <div className="flex items-center justify-between">
                  <span className="font-medium text-sm">{run.inputs.brand_name || 'Untitled'}</span>
                  <div className="flex items-center gap-2">
                    <Badge variant={run.status === 'completed' ? 'success' : run.status === 'processing' ? 'info' : 'warning'} appearance="outline" className="text-xs">
                      v{run.version}
                    </Badge>
                    <span className="text-xs text-muted-foreground">{new Date(run.created_at).toLocaleDateString()}</span>
                  </div>
                </div>
              </button>
            ))}
          </CardContent>
        </Card>
      )}

      <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">Campaign Details</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Brand Name *</Label>
                <Input placeholder="e.g. Nike Saudi Arabia" value={form.brand_name} onChange={e => setForm({ ...form, brand_name: e.target.value })} />
              </div>
              <div>
                <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Campaign Goal</Label>
                <Textarea placeholder="What do you want to achieve?" value={form.campaign_goal} onChange={e => setForm({ ...form, campaign_goal: e.target.value })} rows={2} />
              </div>
              <div>
                <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Target Audience</Label>
                <Textarea placeholder="Describe your target audience" value={form.target_audience} onChange={e => setForm({ ...form, target_audience: e.target.value })} rows={2} />
              </div>
              <div>
                <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Platforms</Label>
                <div className="flex flex-wrap gap-2">
                  {PLATFORM_OPTIONS.map(p => (
                    <button key={p} onClick={() => toggleArrayItem('target_platforms', p)}
                      className={`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${form.target_platforms?.includes(p) ? 'bg-primary text-primary-foreground border-primary' : 'bg-background hover:bg-muted'}`}>
                      {p}
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Target Countries</Label>
                <div className="flex flex-wrap gap-2">
                  {COUNTRY_OPTIONS.map(c => (
                    <button key={c.code} onClick={() => toggleArrayItem('target_countries', c.code)}
                      className={`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${form.target_countries?.includes(c.code) ? 'bg-primary text-primary-foreground border-primary' : 'bg-background hover:bg-muted'}`}>
                      {c.name}
                    </button>
                  ))}
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Budget Range</Label>
                  <Input placeholder="e.g. 50000-100000 SAR" value={form.budget_range} onChange={e => setForm({ ...form, budget_range: e.target.value })} />
                </div>
                <div>
                  <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Timeline</Label>
                  <Input placeholder="e.g. 6 weeks" value={form.timeline} onChange={e => setForm({ ...form, timeline: e.target.value })} />
                </div>
              </div>
              <div>
                <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Brand Tone</Label>
                <Input placeholder="e.g. energetic, youthful, premium" value={form.brand_tone} onChange={e => setForm({ ...form, brand_tone: e.target.value })} />
              </div>
              <div>
                <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Additional Notes</Label>
                <Textarea placeholder="Any other requirements..." value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} rows={2} />
              </div>
              <Button className="w-full" onClick={handleGenerate} disabled={isPending || !form.brand_name}>
                {isPending ? <Spinner className="size-4 animate-spin mr-2" /> : <RiSparklingLine className="size-4 mr-2" />}
                Generate Strategy
              </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>
          ) : activeResult?.outputs ? (
            <>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Badge variant="success" appearance="outline">v{activeResult.version}</Badge>
                  <span className="text-xs text-muted-foreground">Generated {new Date(activeResult.created_at).toLocaleString()}</span>
                </div>
                <Button variant="outline" size="sm" onClick={handleRegenerate} disabled={isRegenerating}>
                  <RiRefreshLine className="size-4 mr-1.5" />Regenerate
                </Button>
              </div>

              <SectionCard title="Strategy Summary">
                <p className="text-sm text-foreground leading-relaxed">{activeResult.outputs.strategy_summary}</p>
              </SectionCard>

              {activeResult.outputs.recommended_platforms?.length > 0 && (
                <SectionCard title="Recommended Platforms">
                  <div className="flex flex-wrap gap-2">
                    {activeResult.outputs.recommended_platforms.map(p => (
                      <Badge key={p} variant="info" appearance="outline">{p}</Badge>
                    ))}
                  </div>
                </SectionCard>
              )}

              {activeResult.outputs.content_pillars?.length > 0 && (
                <SectionCard title="Content Pillars">
                  <div className="grid gap-2">
                    {activeResult.outputs.content_pillars.map((pillar, i) => (
                      <div key={i} className="flex items-start gap-2">
                        <span className="size-6 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-bold shrink-0">{i + 1}</span>
                        <span className="text-sm">{pillar}</span>
                      </div>
                    ))}
                  </div>
                </SectionCard>
              )}

              {activeResult.outputs.creator_archetypes?.length > 0 && (
                <SectionCard title="Creator Archetypes">
                  <div className="grid gap-3">
                    {activeResult.outputs.creator_archetypes.map((a, i) => (
                      <div key={i} className="p-3 rounded-lg border bg-muted/30">
                        <div className="flex items-center gap-2 mb-1">
                          <span className="font-medium text-sm">{a.archetype}</span>
                          {a.platform && <Badge variant="mono" appearance="outline" className="text-xs">{a.platform}</Badge>}
                        </div>
                        <p className="text-xs text-muted-foreground">{a.description}</p>
                      </div>
                    ))}
                  </div>
                </SectionCard>
              )}

              {activeResult.outputs.timeline_phases?.length > 0 && (
                <SectionCard title="Timeline">
                  <div className="space-y-3">
                    {activeResult.outputs.timeline_phases.map((phase, i) => (
                      <div key={i} className="flex gap-3">
                        <div className="flex flex-col items-center">
                          <div className="size-3 rounded-full bg-primary" />
                          {i < activeResult.outputs!.timeline_phases.length - 1 && <div className="w-px flex-1 bg-border" />}
                        </div>
                        <div className="pb-4">
                          <div className="font-medium text-sm">{phase.phase}</div>
                          <div className="text-xs text-muted-foreground mb-1">{phase.duration}</div>
                          <ul className="text-xs space-y-0.5 text-muted-foreground">
                            {phase.activities?.map((a, j) => <li key={j}>• {a}</li>)}
                          </ul>
                        </div>
                      </div>
                    ))}
                  </div>
                </SectionCard>
              )}

              {activeResult.outputs.kpi_targets && Object.keys(activeResult.outputs.kpi_targets).length > 0 && (
                <SectionCard title="KPI Targets">
                  <div className="grid grid-cols-2 gap-3">
                    {Object.entries(activeResult.outputs.kpi_targets).map(([key, val]) => (
                      <div key={key} className="p-3 rounded-lg border text-center">
                        <div className="text-lg font-bold text-foreground">{val}</div>
                        <div className="text-xs text-muted-foreground capitalize">{key.replace(/_/g, ' ')}</div>
                      </div>
                    ))}
                  </div>
                </SectionCard>
              )}

              {activeResult.outputs.budget_allocation && Object.keys(activeResult.outputs.budget_allocation).length > 0 && (
                <SectionCard title="Budget Allocation">
                  <div className="space-y-2">
                    {Object.entries(activeResult.outputs.budget_allocation).map(([key, val]) => (
                      <div key={key} className="flex items-center justify-between text-sm">
                        <span className="text-muted-foreground capitalize">{key.replace(/_/g, ' ')}</span>
                        <span className="font-semibold">{typeof val === 'number' ? `${val}%` : val}</span>
                      </div>
                    ))}
                  </div>
                </SectionCard>
              )}
            </>
          ) : (
            <Card>
              <CardContent>
                <EmptyState title="No Strategy Yet" description="Fill in campaign details and generate your AI-powered strategy." />
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}
