import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { useQuery } from '@tanstack/react-query';
import { api } from '../../shared/lib/apiClient';
import { unwrapArray } from '../../shared/lib/apiShape';
import { useStudioProperties } from '../../shared/hooks/useStudio';
import styles from './StudioPillar.module.css';

export default function StudioPillar() {
  const [section, setSection] = useState<'properties' | 'campaigns'>('properties');

  return (
    <div className={styles.root}>
      <div className={styles.header}>
        <div>
          <h1 className={styles.title}>Studio</h1>
          <p className={styles.subtitle}>Asset & Marketing Hub</p>
        </div>
        <div className={styles.tabs}>
          <button
            className={section === 'properties' ? styles.tabActive : styles.tab}
            onClick={() => setSection('properties')}
          >
            Properties
          </button>
          <button
            className={section === 'campaigns' ? styles.tabActive : styles.tab}
            onClick={() => setSection('campaigns')}
          >
            Campaigns
          </button>
        </div>
      </div>

      {section === 'properties' && <PropertiesSection />}
      {section === 'campaigns' && <CampaignsSection />}
    </div>
  );
}

function PropertiesSection() {
  const navigate = useNavigate();
  const { properties, isLoading } = useStudioProperties();

  if (isLoading) {
    return (
      <div className={styles.propGrid}>
        {[0, 1, 2, 3, 4, 5].map((i) => (
          <div key={i} className={`${styles.propSkeleton} shimmer`} />
        ))}
      </div>
    );
  }

  return (
    <div className={styles.propGrid}>
      {(properties || []).map((prop, i) => (
        <motion.button
          key={prop.id}
          className={`${styles.propCard} glass-card`}
          onClick={() => navigate(`/studio/${prop.id}`)}
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ delay: i * 0.05, duration: 0.3 }}
          whileHover={{ scale: 1.03, y: -4 }}
          whileTap={{ scale: 0.99 }}
          aria-label={`View ${prop.name}`}
        >
          <div className={styles.propThumb}>
            {prop.thumbnailUrl ? (
              <img src={prop.thumbnailUrl} alt={prop.name} />
            ) : (
              <div className={styles.thumbPlaceholder}>Property</div>
            )}
            {prop.availableUnits !== undefined && (
              <span className={styles.availBadge}>{prop.availableUnits} available</span>
            )}
          </div>
          <div className={styles.propMeta}>
            <span className={styles.propName}>{prop.name}</span>
            <span className={styles.propSub}>{prop.location}</span>
            {prop.priceRange && <span className={styles.propPrice}>{prop.priceRange}</span>}
          </div>
        </motion.button>
      ))}
    </div>
  );
}

interface CampaignSummary {
  id: string;
  name: string;
  platform: string;
  status: string;
  budget: number;
  spent: number;
  impressions: number;
  clicks: number;
  conversions: number;
  objective: string;
  bid_strategy: string;
}

function CampaignsSection() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['studio-campaigns'],
    queryFn: async () => {
      const response = await api.get<unknown>('/catalyst/campaigns?limit=100&offset=0');
      return unwrapArray<CampaignSummary>(response);
    },
    staleTime: 60_000,
    refetchOnMount: 'always',
  });
  const campaigns = data ?? [];

  if (isLoading) {
    return (
      <div className={styles.campaignGrid}>
        {[0, 1, 2].map((i) => (
          <div key={i} className={`${styles.campaignSkeleton} shimmer`} />
        ))}
      </div>
    );
  }

  if (error) {
    return (
      <div className={styles.emptyState}>
        Campaign data is unavailable. Check the Catalyst API route and Meta provider configuration.
      </div>
    );
  }

  if (campaigns.length === 0) {
    return <div className={styles.emptyState}>No campaigns found.</div>;
  }

  return (
    <div className={styles.campaignGrid}>
      {campaigns.map((campaign, index) => (
        <motion.article
          key={campaign.id}
          className={`${styles.campaignCard} glass-card`}
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: index * 0.05, duration: 0.28 }}
        >
          <div className={styles.campaignTop}>
            <div>
              <span className={styles.campaignName}>{campaign.name}</span>
              <span className={styles.campaignMeta}>
                {campaign.platform} - {campaign.objective}
              </span>
            </div>
            <span className={styles.campaignStatus}>{campaign.status}</span>
          </div>
          <div className={styles.campaignStats}>
            <Metric label="Budget" value={formatMoney(campaign.budget)} />
            <Metric label="Spent" value={formatMoney(campaign.spent)} />
            <Metric label="Impressions" value={formatNumber(campaign.impressions)} />
            <Metric label="Clicks" value={formatNumber(campaign.clicks)} />
            <Metric label="Leads" value={formatNumber(campaign.conversions)} />
          </div>
          <div className={styles.campaignFooter}>
            Bid strategy: {campaign.bid_strategy || 'provider default'}
          </div>
        </motion.article>
      ))}
    </div>
  );
}

function Metric({ label, value }: { label: string; value: string }) {
  return (
    <span className={styles.campaignStat}>
      <small>{label}</small>
      <strong>{value}</strong>
    </span>
  );
}

function formatMoney(value: number): string {
  return new Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'INR',
    maximumFractionDigits: 0,
  }).format(Number(value || 0));
}

function formatNumber(value: number): string {
  return new Intl.NumberFormat('en-IN').format(Number(value || 0));
}
