'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 {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select';
import { RiSparklingLine, RiRefreshLine, RiFileCopyLine, RiCheckLine } from '@remixicon/react';
import { useGenerateOutreachDraft, useRegenerateOutreachDraft } from '../../hooks';
import { SectionCard, EmptyState, LoadingSkeleton } from '../shared/ScoreBar';
import type { OutreachDraft } from '../../types';

export function OutreachWriterPanel() {
  const [form, setForm] = useState({
    influencer_id: '', outreach_type: 'paid', tone: 'professional',
    channel: 'email', cta_type: '', brand_voice_notes: '',
    campaign_name: '', campaign_objective: '',
  });
  const [result, setResult] = useState<OutreachDraft | null>(null);
  const [copiedField, setCopiedField] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'full' | 'short' | 'followup'>('full');

  const { mutateAsync: generate, isPending } = useGenerateOutreachDraft();
  const { mutateAsync: regenerate, isPending: isRegenerating } = useRegenerateOutreachDraft();

  const handleGenerate = async () => {
    if (!form.influencer_id) return;
    const data: Parameters<typeof generate>[0] = {
      influencer_id: Number(form.influencer_id),
      outreach_type: form.outreach_type,
      tone: form.tone,
      channel: form.channel,
    };
    if (form.cta_type) data.cta_type = form.cta_type;
    if (form.brand_voice_notes) data.brand_voice_notes = form.brand_voice_notes;
    if (form.campaign_name || form.campaign_objective) {
      data.campaign_context = {};
      if (form.campaign_name) data.campaign_context.name = form.campaign_name;
      if (form.campaign_objective) data.campaign_context.objective = form.campaign_objective;
    }
    const res = await generate(data);
    setResult(res);
  };

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

  const copyToClipboard = (text: string, field: string) => {
    navigator.clipboard.writeText(text);
    setCopiedField(field);
    setTimeout(() => setCopiedField(null), 2000);
  };

  const draftContent = activeTab === 'full' ? result?.outreach_message :
    activeTab === 'short' ? result?.short_variant : result?.follow_up_variant;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground">AI Outreach Writer</h1>
        <p className="text-sm text-muted-foreground mt-1">Generate personalized outreach messages for creators</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">Outreach Settings</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Creator ID *</Label>
                <Input type="number" placeholder="Influencer ID" value={form.influencer_id} onChange={e => setForm({ ...form, influencer_id: 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">Type</Label>
                  <Select value={form.outreach_type} onValueChange={v => setForm({ ...form, outreach_type: v })}>
                    <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="paid">Paid</SelectItem>
                      <SelectItem value="gifting">Gifting</SelectItem>
                      <SelectItem value="affiliate">Affiliate</SelectItem>
                      <SelectItem value="ambassador">Ambassador</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Tone</Label>
                  <Select value={form.tone} onValueChange={v => setForm({ ...form, tone: v })}>
                    <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="professional">Professional</SelectItem>
                      <SelectItem value="warm">Warm</SelectItem>
                      <SelectItem value="premium">Premium</SelectItem>
                      <SelectItem value="casual">Casual</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Channel</Label>
                  <Select value={form.channel} onValueChange={v => setForm({ ...form, channel: v })}>
                    <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="email">Email</SelectItem>
                      <SelectItem value="dm">Direct Message</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">CTA</Label>
                  <Input className="h-9" placeholder="e.g. schedule a call" value={form.cta_type} onChange={e => setForm({ ...form, cta_type: e.target.value })} />
                </div>
              </div>
              <div>
                <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Campaign Name</Label>
                <Input placeholder="Campaign context" value={form.campaign_name} onChange={e => setForm({ ...form, campaign_name: e.target.value })} />
              </div>
              <div>
                <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Brand Voice Notes</Label>
                <Textarea placeholder="How should the message sound?" value={form.brand_voice_notes} onChange={e => setForm({ ...form, brand_voice_notes: e.target.value })} rows={2} />
              </div>
              <Button className="w-full" onClick={handleGenerate} disabled={isPending || !form.influencer_id}>
                {isPending ? <Spinner className="size-4 animate-spin mr-2" /> : <RiSparklingLine className="size-4 mr-2" />}
                Generate Draft
              </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>
          ) : result ? (
            <>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Badge variant="info" appearance="outline" className="capitalize">{result.outreach_type}</Badge>
                  <Badge variant="mono" appearance="outline" className="capitalize">{result.tone}</Badge>
                  <Badge variant="mono" appearance="outline">v{result.version}</Badge>
                </div>
                <Button variant="outline" size="sm" onClick={handleRegenerate}>
                  <RiRefreshLine className="size-4 mr-1.5" />Regenerate
                </Button>
              </div>

              {result.subject_line && (
                <SectionCard title="Subject Line" action={
                  <Button variant="ghost" size="sm" className="h-7 px-2" onClick={() => copyToClipboard(result.subject_line, 'subject')}>
                    {copiedField === 'subject' ? <RiCheckLine className="size-3.5 text-emerald-500" /> : <RiFileCopyLine className="size-3.5" />}
                  </Button>
                }>
                  <p className="text-sm font-medium">{result.subject_line}</p>
                </SectionCard>
              )}

              <Card>
                <div className="border-b px-1 pt-1">
                  <div className="flex">
                    {(['full', 'short', 'followup'] as const).map(tab => (
                      <button key={tab} onClick={() => setActiveTab(tab)}
                        className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${activeTab === tab ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'}`}>
                        {tab === 'full' ? 'Full Draft' : tab === 'short' ? 'Short Version' : 'Follow-up'}
                      </button>
                    ))}
                  </div>
                </div>
                <CardContent className="pt-4">
                  <div className="flex justify-end mb-2">
                    <Button variant="ghost" size="sm" className="h-7 px-2" onClick={() => copyToClipboard(draftContent || '', activeTab)}>
                      {copiedField === activeTab ? <><RiCheckLine className="size-3.5 text-emerald-500 mr-1" />Copied</> : <><RiFileCopyLine className="size-3.5 mr-1" />Copy</>}
                    </Button>
                  </div>
                  <div className="bg-muted/30 rounded-lg p-4 text-sm leading-relaxed whitespace-pre-wrap">{draftContent}</div>
                </CardContent>
              </Card>

              {result.personalization_points?.length > 0 && (
                <SectionCard title="Personalization Points">
                  <div className="flex flex-wrap gap-2">
                    {result.personalization_points.map((p, i) => (
                      <Badge key={i} variant="info" appearance="outline" className="text-xs">{p}</Badge>
                    ))}
                  </div>
                </SectionCard>
              )}
            </>
          ) : (
            <Card><CardContent><EmptyState title="No Draft Yet" description="Configure outreach settings and generate a personalized message." /></CardContent></Card>
          )}
        </div>
      </div>
    </div>
  );
}
