import { useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react';
import Box from '@mui/material/Box';
import { PackagesStep } from './PackagesStep';
import type { NearbyVerifiedPackage, PackageData, PackagesStepProvider } from './PackagesStep';
import { Navigation } from '../../organisms/Navigation';

// ─── Helpers ─────────────────────────────────────────────────────────────────

const FALogo = () => (
  <Box sx={{ display: 'flex', alignItems: 'center' }}>
    <Box
      component="img"
      src="/brandlogo/logo-full.svg"
      alt="Funeral Arranger"
      sx={{ height: 28, display: { xs: 'none', md: 'block' } }}
    />
    <Box
      component="img"
      src="/brandlogo/logo-short.svg"
      alt="Funeral Arranger"
      sx={{ height: 28, display: { xs: 'block', md: 'none' } }}
    />
  </Box>
);

const nav = (
  <Navigation
    logo={<FALogo />}
    items={[
      { label: 'FAQ', href: '/faq' },
      { label: 'Contact Us', href: '/contact' },
      { label: 'Log in', href: '/login' },
    ]}
  />
);

// ─── Mock data ───────────────────────────────────────────────────────────────

const verifiedProvider: PackagesStepProvider = {
  name: 'H.Parsons Funeral Directors',
  location: 'Wentworth, NSW',
  imageUrl: '/images/placeholder/hparsonsvenue.jpg',
  rating: 4.6,
  reviewCount: 7,
};

const unverifiedProvider: PackagesStepProvider = {
  name: 'H.Parsons Funeral Directors',
  location: 'Wentworth, NSW',
  rating: 4.6,
  reviewCount: 7,
};

const matchedPackages: PackageData[] = [
  {
    id: 'everyday',
    name: 'Everyday Funeral Package',
    price: 2700,
    description:
      'This package includes a funeral service at a chapel or a church with a funeral procession. It includes many of the most commonly selected funeral options.',
    sections: [
      {
        heading: 'Essentials',
        items: [
          { name: 'Accommodation', price: 500 },
          { name: 'Death registration certificate', price: 150 },
          { name: 'Doctor fee for Cremation', price: 150 },
          { name: 'NSW Government Levy - Cremation', price: 83 },
          { name: 'Professional Mortuary Care', price: 1200 },
          { name: 'Professional Service Fee', price: 1120 },
        ],
      },
      {
        heading: 'Complimentary Items',
        items: [
          { name: 'Dressing Fee', price: 0 },
          { name: 'Viewing Fee', price: 0 },
        ],
      },
    ],
    total: 2700,
    extras: {
      heading: 'Extras',
      items: [
        { name: 'Allowance for Flowers', price: 150, isAllowance: true },
        { name: 'Allowance for Master of Ceremonies', price: 500, isAllowance: true },
        { name: 'After Business Hours Service Surcharge', price: 150 },
        { name: 'After Hours Prayers', price: 1920 },
        { name: 'Coffin Bearing by Funeral Directors', price: 1500 },
        { name: 'Digital Recording', price: 500 },
      ],
    },
    terms:
      'This package includes a funeral service at a chapel or a church with a funeral procession. Pricing may vary based on additional selections.',
  },
  {
    id: 'essential',
    name: 'Essential Funeral Package',
    price: 1800,
    description:
      'A simple, dignified option covering the essential requirements for a cremation service.',
    sections: [
      {
        heading: 'Essentials',
        items: [
          { name: 'Death registration certificate', price: 150 },
          { name: 'Professional Mortuary Care', price: 800 },
          { name: 'Professional Service Fee', price: 850 },
        ],
      },
    ],
    total: 1800,
  },
];

const otherPackages: PackageData[] = [
  {
    id: 'deluxe',
    name: 'Deluxe Funeral Package',
    price: 4900,
    description:
      'A comprehensive package with premium inclusions, higher-quality coffin selection, and expanded service options for families wanting a more personalised farewell.',
    sections: [
      {
        heading: 'Essentials',
        items: [
          { name: 'Accommodation', price: 750 },
          { name: 'Death registration certificate', price: 150 },
          { name: 'Professional Mortuary Care', price: 1500 },
          { name: 'Professional Service Fee', price: 1500 },
          { name: 'Premium Coffin', price: 1000 },
        ],
      },
    ],
    total: 4900,
  },
  {
    id: 'catholic',
    name: 'Catholic Service',
    price: 3200,
    description:
      'Tailored for Catholic funeral traditions including a Requiem Mass, graveside prayers, and coordination with parish requirements.',
    sections: [
      {
        heading: 'Essentials',
        items: [
          { name: 'Accommodation', price: 500 },
          { name: 'Professional Mortuary Care', price: 1200 },
          { name: 'Professional Service Fee', price: 1200 },
          { name: 'Church coordination', price: 300 },
        ],
      },
    ],
    total: 3200,
  },
];

const manyOtherPackages: PackageData[] = [
  ...otherPackages,
  {
    id: 'memorial',
    name: 'Memorial Service',
    price: 2400,
    description: 'A celebration-of-life service without burial or cremation on the same day.',
    sections: [
      {
        heading: 'Essentials',
        items: [
          { name: 'Professional Service Fee', price: 1200 },
          { name: 'Venue coordination', price: 600 },
          { name: 'Memorial book', price: 100 },
        ],
      },
    ],
    total: 2400,
  },
  {
    id: 'graveside',
    name: 'Graveside Service',
    price: 2900,
    description: 'A simple graveside committal, ideal for smaller family gatherings.',
    sections: [
      {
        heading: 'Essentials',
        items: [
          { name: 'Professional Mortuary Care', price: 1000 },
          { name: 'Professional Service Fee', price: 1100 },
          { name: 'Cemetery coordination', price: 400 },
        ],
      },
    ],
    total: 2900,
  },
  {
    id: 'prepaid-basic',
    name: 'Prepaid Basic Plan',
    price: 3600,
    description: 'Lock in today’s price for a basic cremation package, paid over 12 months.',
    sections: [
      {
        heading: 'Essentials',
        items: [
          { name: 'Locked-in pricing', price: 0, priceLabel: 'Complimentary' },
          { name: 'Professional Service Fee', price: 1200 },
          { name: 'Professional Mortuary Care', price: 1000 },
        ],
      },
    ],
    total: 3600,
  },
];

const nearbyVerifiedPackages: NearbyVerifiedPackage[] = [
  {
    id: 'rankins-standard',
    packageName: 'Standard Cremation Package',
    price: 2450,
    providerName: 'Rankins Funerals',
    location: 'Warrawong, NSW',
    rating: 4.8,
    reviewCount: 23,
  },
  {
    id: 'easy-essential',
    packageName: 'Essential Funeral Service',
    price: 1950,
    providerName: 'Easy Funerals',
    location: 'Sydney, NSW',
    rating: 4.5,
    reviewCount: 42,
  },
  {
    id: 'killick-classic',
    packageName: 'Classic Farewell Package',
    price: 3100,
    providerName: 'Killick Family Funerals',
    location: 'Shellharbour, NSW',
    rating: 4.9,
    reviewCount: 15,
  },
];

const tier2Packages: PackageData[] = [
  {
    id: 't2-standard',
    name: 'Standard Funeral Service',
    price: 5200,
    description:
      'A full-service package based on publicly available information. Breakdown not available — make an enquiry to confirm what is included.',
    sections: [],
  },
  {
    id: 't2-basic',
    name: 'Basic Cremation',
    price: 3400,
    description:
      'An entry-level package based on publicly available information. Pricing is indicative only.',
    sections: [],
  },
];

// ─── Meta ────────────────────────────────────────────────────────────────────

const meta: Meta<typeof PackagesStep> = {
  title: 'Pages/PackagesStep',
  component: PackagesStep,
  tags: ['autodocs'],
  parameters: {
    layout: 'fullscreen',
  },
};

export default meta;
type Story = StoryObj<typeof PackagesStep>;

// ─── Verified ────────────────────────────────────────────────────────────────

/** Verified provider — matching packages + up to 3 other packages from the same provider */
export const Verified: Story = {
  render: () => {
    const [selectedId, setSelectedId] = useState<string | null>('everyday');

    return (
      <PackagesStep
        provider={verifiedProvider}
        providerTier="verified"
        packages={matchedPackages}
        secondaryList={{ kind: 'same-provider-more', packages: otherPackages }}
        selectedPackageId={selectedId}
        onSelectPackage={setSelectedId}
        onArrange={() => alert('Open ArrangementDialog')}
        onCompare={() => alert('Open compare view')}
        onProviderClick={() => alert('Open provider profile (future)')}
        onBack={() => alert('Back')}
        navigation={nav}
      />
    );
  },
};

// ─── Verified — with "See all" link ─────────────────────────────────────────

/** Verified provider with 5+ other packages — shows first 3 + "See all N packages" link */
export const VerifiedWithManyOtherPackages: Story = {
  render: () => {
    const [selectedId, setSelectedId] = useState<string | null>('everyday');

    return (
      <PackagesStep
        provider={verifiedProvider}
        providerTier="verified"
        packages={matchedPackages}
        secondaryList={{ kind: 'same-provider-more', packages: manyOtherPackages }}
        selectedPackageId={selectedId}
        onSelectPackage={setSelectedId}
        onArrange={() => alert('Open ArrangementDialog')}
        onSeeAllPackages={() => alert('Route to showAllFromProvider variant')}
        onProviderClick={() => alert('Open provider profile (future)')}
        onBack={() => alert('Back')}
        navigation={nav}
      />
    );
  },
};

// ─── "Show all from provider" variant ───────────────────────────────────────

/** Flat "All packages from [Provider]" view — no grouping, selected package preserved */
export const AllFromProvider: Story = {
  render: () => {
    const [selectedId, setSelectedId] = useState<string | null>('everyday');
    const allPackages = [...matchedPackages, ...manyOtherPackages];

    return (
      <PackagesStep
        provider={verifiedProvider}
        providerTier="verified"
        packages={allPackages}
        showAllFromProvider
        selectedPackageId={selectedId}
        onSelectPackage={setSelectedId}
        onArrange={() => alert('Open ArrangementDialog')}
        onCompare={() => alert('Open compare view')}
        onProviderClick={() => alert('Open provider profile (future)')}
        onBack={() => alert('Back')}
        navigation={nav}
      />
    );
  },
};

// ─── Tier 3 (itemised breakdown) ────────────────────────────────────────────

/** Tier 3 unverified — itemised breakdown + "Make an enquiry" + nearby verified alternatives */
export const Tier3: Story = {
  render: () => {
    const [selectedId, setSelectedId] = useState<string | null>('everyday');

    return (
      <PackagesStep
        provider={unverifiedProvider}
        providerTier="tier3"
        packages={matchedPackages}
        secondaryList={{ kind: 'nearby-verified', packages: nearbyVerifiedPackages }}
        selectedPackageId={selectedId}
        onSelectPackage={setSelectedId}
        onArrange={() => alert('Make an enquiry')}
        onCompare={() => alert('Open compare view')}
        onNearbyPackageClick={(id) => alert(`Route to nearby package: ${id}`)}
        onProviderClick={() => alert('Open provider profile (future)')}
        onBack={() => alert('Back')}
        navigation={nav}
      />
    );
  },
};

// ─── Tier 2 (price only, no breakdown) ──────────────────────────────────────

/** Tier 2 unverified — price only, detail panel shows "Itemised Pricing Unavailable" */
export const Tier2: Story = {
  render: () => {
    const [selectedId, setSelectedId] = useState<string | null>('t2-standard');

    return (
      <PackagesStep
        provider={unverifiedProvider}
        providerTier="tier2"
        packages={tier2Packages}
        secondaryList={{ kind: 'nearby-verified', packages: nearbyVerifiedPackages }}
        selectedPackageId={selectedId}
        onSelectPackage={setSelectedId}
        onArrange={() => alert('Make an enquiry')}
        onCompare={() => alert('Open compare view')}
        onNearbyPackageClick={(id) => alert(`Route to nearby package: ${id}`)}
        onProviderClick={() => alert('Open provider profile (future)')}
        onBack={() => alert('Back')}
        navigation={nav}
      />
    );
  },
};

// ─── Edge cases ──────────────────────────────────────────────────────────────

/** No selection yet — empty detail panel */
export const NoSelection: Story = {
  render: () => {
    const [selectedId, setSelectedId] = useState<string | null>(null);

    return (
      <PackagesStep
        provider={verifiedProvider}
        providerTier="verified"
        packages={matchedPackages}
        secondaryList={{ kind: 'same-provider-more', packages: otherPackages }}
        selectedPackageId={selectedId}
        onSelectPackage={setSelectedId}
        onArrange={() => alert('Open ArrangementDialog')}
        onCompare={() => alert('Open compare view')}
        onProviderClick={() => alert('Open provider profile (future)')}
        onBack={() => alert('Back')}
        navigation={nav}
      />
    );
  },
};

/** Verified provider with no "other packages" — primary list only */
export const VerifiedNoSecondary: Story = {
  render: () => {
    const [selectedId, setSelectedId] = useState<string | null>(null);

    return (
      <PackagesStep
        provider={verifiedProvider}
        providerTier="verified"
        packages={matchedPackages}
        selectedPackageId={selectedId}
        onSelectPackage={setSelectedId}
        onArrange={() => alert('Open ArrangementDialog')}
        onCompare={() => alert('Open compare view')}
        onProviderClick={() => alert('Open provider profile (future)')}
        onBack={() => alert('Back')}
        navigation={nav}
      />
    );
  },
};

/** Pre-planning flow — softer copy */
export const PrePlanning: Story = {
  render: () => {
    const [selectedId, setSelectedId] = useState<string | null>(null);

    return (
      <PackagesStep
        provider={verifiedProvider}
        providerTier="verified"
        packages={matchedPackages}
        secondaryList={{ kind: 'same-provider-more', packages: otherPackages }}
        selectedPackageId={selectedId}
        onSelectPackage={setSelectedId}
        onArrange={() => alert('Open ArrangementDialog')}
        onCompare={() => alert('Open compare view')}
        onProviderClick={() => alert('Open provider profile (future)')}
        onBack={() => alert('Back')}
        navigation={nav}
        isPrePlanning
      />
    );
  },
};

/** Validation error */
export const WithError: Story = {
  render: () => {
    const [selectedId, setSelectedId] = useState<string | null>(null);

    return (
      <PackagesStep
        provider={verifiedProvider}
        providerTier="verified"
        packages={matchedPackages}
        selectedPackageId={selectedId}
        onSelectPackage={setSelectedId}
        onArrange={() => {}}
        onBack={() => alert('Back')}
        error="Please choose a package to continue."
        navigation={nav}
      />
    );
  },
};
