'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } 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 {
  RiAddLine, RiSearchLine, RiTimeLine, RiArrowRightSLine,
} from '@remixicon/react';
import { useCreatorCRM, useCreatorCRMSummary, useCreateCRMEntry } from '../../hooks';
import { SectionCard, EmptyState, LoadingSkeleton } from '../shared/ScoreBar';
import type { CRMEntry, CRMStatus, InteractionType } from '../../types';

const STATUSES: { value: CRMStatus; label: string; color: string }[] = [
  { value: 'prospect', label: 'Prospect', color: 'bg-gray-100 text-gray-700' },
  { value: 'shortlisted', label: 'Shortlisted', color: 'bg-blue-100 text-blue-700' },
  { value: 'contacted', label: 'Contacted', color: 'bg-indigo-100 text-indigo-700' },
  { value: 'interested', label: 'Interested', color: 'bg-emerald-100 text-emerald-700' },
  { value: 'negotiating', label: 'Negotiating', color: 'bg-amber-100 text-amber-700' },
  { value: 'no_response', label: 'No Response', color: 'bg-red-100 text-red-700' },
  { value: 'active', label: 'Active', color: 'bg-green-100 text-green-700' },
  { value: 'archived', label: 'Archived', color: 'bg-gray-100 text-gray-500' },
];

const INTERACTION_TYPES: { value: InteractionType; label: string }[] = [
  { value: 'outreach_sent', label: 'Outreach Sent' },
  { value: 'response_received', label: 'Response Received' },
  { value: 'call_scheduled', label: 'Call Scheduled' },
  { value: 'call_completed', label: 'Call Completed' },
  { value: 'negotiation', label: 'Negotiation' },
  { value: 'contract_sent', label: 'Contract Sent' },
  { value: 'contract_signed', label: 'Contract Signed' },
  { value: 'content_review', label: 'Content Review' },
  { value: 'content_approved', label: 'Content Approved' },
  { value: 'payment', label: 'Payment' },
  { value: 'note', label: 'Note' },
  { value: 'status_change', label: 'Status Change' },
];

function StatusBadge({ status }: { status: string }) {
  const s = STATUSES.find(st => st.value === status);
  return (
    <span className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium ${s?.color ?? 'bg-gray-100 text-gray-700'}`}>
      {s?.label ?? status}
    </span>
  );
}

export function CreatorCRMPanel() {
  const [influencerId, setInfluencerId] = useState('');
  const [activeInfluencer, setActiveInfluencer] = useState<number | null>(null);
  const [showAddForm, setShowAddForm] = useState(false);
  const [newEntry, setNewEntry] = useState({
    interaction_type: 'note' as InteractionType,
    status: '' as CRMStatus | '',
    note: '',
    next_step: '',
  });

  const { data: timeline, isLoading: timelineLoading } = useCreatorCRM(activeInfluencer ?? 0);
  const { data: summary, isLoading: summaryLoading } = useCreatorCRMSummary(activeInfluencer ?? 0);
  const { mutateAsync: createEntry, isPending: isCreating } = useCreateCRMEntry();

  const handleSearch = () => {
    const id = Number(influencerId);
    if (id > 0) setActiveInfluencer(id);
  };

  const handleAddEntry = async () => {
    if (!activeInfluencer) return;
    const data: Parameters<typeof createEntry>[0] = {
      influencer_id: activeInfluencer,
      interaction_type: newEntry.interaction_type,
    };
    if (newEntry.status) data.status = newEntry.status;
    if (newEntry.note) data.note = newEntry.note;
    if (newEntry.next_step) data.next_step = newEntry.next_step;
    await createEntry(data);
    setNewEntry({ interaction_type: 'note', status: '', note: '', next_step: '' });
    setShowAddForm(false);
  };

  const timelineEntries = (timeline as { data?: CRMEntry[] })?.data ?? (Array.isArray(timeline) ? timeline : []);

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground">Creator CRM</h1>
        <p className="text-sm text-muted-foreground mt-1">Track creator relationships and interactions</p>
      </div>

      <Card>
        <CardContent className="pt-5">
          <div className="flex gap-3">
            <Input
              type="number"
              placeholder="Enter Creator / Influencer ID"
              value={influencerId}
              onChange={e => setInfluencerId(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && handleSearch()}
              className="max-w-xs"
            />
            <Button onClick={handleSearch} disabled={!influencerId}>
              <RiSearchLine className="size-4 mr-1.5" />View CRM
            </Button>
          </div>
        </CardContent>
      </Card>

      {activeInfluencer && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div className="lg:col-span-1 space-y-4">
            {summaryLoading ? (
              <Card><CardContent className="py-6"><LoadingSkeleton rows={3} /></CardContent></Card>
            ) : summary ? (
              <>
                <SectionCard title="Relationship Summary">
                  <div className="space-y-3">
                    <div className="flex items-center justify-between">
                      <span className="text-sm text-muted-foreground">Current Status</span>
                      <StatusBadge status={summary.current_status} />
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-sm text-muted-foreground">Total Interactions</span>
                      <span className="text-sm font-bold tabular-nums">{summary.total_interactions}</span>
                    </div>
                    {summary.next_step && (
                      <div className="p-3 rounded-lg bg-blue-50 border border-blue-100">
                        <div className="text-xs font-medium text-blue-700 mb-0.5">Next Step</div>
                        <div className="text-sm text-blue-900">{summary.next_step}</div>
                      </div>
                    )}
                    {summary.latest_interaction && (
                      <div className="text-xs text-muted-foreground">
                        Last: {summary.latest_interaction.type.replace(/_/g, ' ')} — {new Date(summary.latest_interaction.date).toLocaleDateString()}
                      </div>
                    )}
                  </div>
                </SectionCard>

                {summary.interaction_types && Object.keys(summary.interaction_types).length > 0 && (
                  <SectionCard title="Interaction Breakdown">
                    <div className="space-y-1.5">
                      {Object.entries(summary.interaction_types).map(([type, count]) => (
                        <div key={type} className="flex items-center justify-between text-sm">
                          <span className="text-muted-foreground capitalize">{type.replace(/_/g, ' ')}</span>
                          <span className="font-medium tabular-nums">{count as number}</span>
                        </div>
                      ))}
                    </div>
                  </SectionCard>
                )}

                {summary.status_history?.length > 0 && (
                  <SectionCard title="Status History">
                    <div className="space-y-2">
                      {summary.status_history.map((h, i) => (
                        <div key={i} className="flex items-center gap-2 text-xs">
                          <StatusBadge status={h.from} />
                          <RiArrowRightSLine className="size-3 text-muted-foreground shrink-0" />
                          <StatusBadge status={h.to} />
                          <span className="text-muted-foreground ml-auto">{new Date(h.date).toLocaleDateString()}</span>
                        </div>
                      ))}
                    </div>
                  </SectionCard>
                )}
              </>
            ) : (
              <Card><CardContent><EmptyState title="No CRM Data" description="No relationship data found for this creator." /></CardContent></Card>
            )}
          </div>

          <div className="lg:col-span-2 space-y-4">
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-semibold">Timeline</h2>
              <Button size="sm" onClick={() => setShowAddForm(!showAddForm)}>
                <RiAddLine className="size-4 mr-1.5" />Add Entry
              </Button>
            </div>

            {showAddForm && (
              <Card className="border-primary/30 bg-primary/5">
                <CardContent className="pt-5 space-y-3">
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Interaction Type</Label>
                      <Select value={newEntry.interaction_type} onValueChange={v => setNewEntry({ ...newEntry, interaction_type: v as InteractionType })}>
                        <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                        <SelectContent>
                          {INTERACTION_TYPES.map(t => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Status</Label>
                      <Select value={newEntry.status || 'none'} onValueChange={v => setNewEntry({ ...newEntry, status: (v === 'none' ? '' : v) as CRMStatus | '' })}>
                        <SelectTrigger className="h-9"><SelectValue placeholder="No change" /></SelectTrigger>
                        <SelectContent>
                          <SelectItem value="none">No Change</SelectItem>
                          {STATUSES.map(s => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  <div>
                    <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Note</Label>
                    <Textarea placeholder="What happened?" value={newEntry.note} onChange={e => setNewEntry({ ...newEntry, note: e.target.value })} rows={2} />
                  </div>
                  <div>
                    <Label className="text-xs font-medium text-muted-foreground mb-1.5 block">Next Step</Label>
                    <Input placeholder="What's the next action?" value={newEntry.next_step} onChange={e => setNewEntry({ ...newEntry, next_step: e.target.value })} />
                  </div>
                  <div className="flex gap-2 justify-end">
                    <Button variant="outline" size="sm" onClick={() => setShowAddForm(false)}>Cancel</Button>
                    <Button size="sm" onClick={handleAddEntry} disabled={isCreating}>
                      {isCreating && <Spinner className="size-4 animate-spin mr-1.5" />}Save Entry
                    </Button>
                  </div>
                </CardContent>
              </Card>
            )}

            {timelineLoading ? (
              <LoadingSkeleton rows={4} />
            ) : timelineEntries.length > 0 ? (
              <div className="space-y-0">
                {timelineEntries.map((entry: CRMEntry, i: number) => (
                  <div key={entry.id} className="flex gap-4">
                    <div className="flex flex-col items-center">
                      <div className="size-3 rounded-full bg-primary mt-1.5" />
                      {i < timelineEntries.length - 1 && <div className="w-px flex-1 bg-border" />}
                    </div>
                    <div className="pb-6 flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <Badge variant="mono" appearance="outline" className="text-xs capitalize">{entry.interaction_type.replace(/_/g, ' ')}</Badge>
                        {entry.status && <StatusBadge status={entry.status} />}
                        <span className="text-xs text-muted-foreground ml-auto">{new Date(entry.created_at).toLocaleString()}</span>
                      </div>
                      {entry.note && <p className="text-sm text-foreground mt-1">{entry.note}</p>}
                      {entry.next_step && (
                        <div className="mt-2 text-xs text-blue-700 bg-blue-50 px-2.5 py-1.5 rounded inline-flex items-center gap-1">
                          <RiTimeLine className="size-3" />Next: {entry.next_step}
                        </div>
                      )}
                      {entry.created_by && <div className="text-xs text-muted-foreground mt-1">by {entry.created_by.name}</div>}
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <EmptyState title="No Timeline Entries" description="Add the first interaction to start tracking this relationship." action={
                <Button size="sm" onClick={() => setShowAddForm(true)}><RiAddLine className="size-4 mr-1.5" />Add Entry</Button>
              } />
            )}
          </div>
        </div>
      )}
    </div>
  );
}
