import { useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react';
import Box from '@mui/material/Box';
import { PackageDetail } from './PackageDetail';
import { ServiceOption } from '../../molecules/ServiceOption';
import { ProviderCardCompact } from '../../molecules/ProviderCardCompact';
import { Chip } from '../../atoms/Chip';
import { Typography } from '../../atoms/Typography';
import { Button } from '../../atoms/Button';
import { Navigation } from '../Navigation';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';

const DEMO_IMAGE =
  'https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=400&h=300&fit=crop';

const essentials = [
  {
    name: 'Allowance for Coffin',
    price: 1750,
    isAllowance: true,
    info: 'Allowance amount — upgrade options available during arrangement.',
  },
  {
    name: 'Cremation Certificate/Permit',
    price: 350,
    info: 'Statutory medical referee fee required for all cremations in NSW.',
  },
  {
    name: 'Crematorium: Mackay Family Crematorium',
    price: 660,
    info: 'Cremation facility fees at the selected crematorium.',
  },
  {
    name: 'Death Registration Certificate',
    price: 70,
    info: 'Lodgement of death registration with NSW Registry of Births, Deaths & Marriages.',
  },
  {
    name: 'Dressing Fee',
    price: 0,
    priceLabel: 'Complimentary',
    info: 'Dressing and preparation of the deceased — included at no charge.',
  },
  {
    name: 'NSW Government Levy — Cremation',
    price: 45.1,
    info: 'NSW Government cremation levy as set by the Department of Health.',
  },
  {
    name: 'Professional Mortuary Care',
    price: 440,
    info: 'Preparation and care of the deceased.',
  },
  {
    name: 'Professional Service Fee',
    price: 3650.9,
    info: 'Coordination of all funeral arrangements and services.',
  },
  {
    name: 'Transportation Service Fee',
    price: 0,
    priceLabel: 'Complimentary',
    info: 'Transfer of the deceased to the funeral home — included in this package.',
  },
];

const optionals = [
  {
    name: 'Digital Recording of the Funeral Service',
    priceLabel: 'Complimentary',
    info: 'Professional video recording of the funeral service.',
  },
  {
    name: 'Online Notice',
    priceLabel: 'Complimentary',
    info: 'Online death notice published on the funeral home website.',
  },
  {
    name: 'Viewing Fee',
    priceLabel: 'Complimentary',
    info: 'One private family viewing — included at no charge.',
  },
  {
    name: 'Webstreaming of the Funeral Service',
    priceLabel: 'Complimentary',
    info: 'Live webstream of the funeral service for remote attendees.',
  },
];

const extras = {
  heading: 'Extras',
  items: [
    {
      name: 'Allowance for Celebrant',
      price: 550,
      isAllowance: true,
      info: 'Professional celebrant or MC for the funeral service.',
    },
    {
      name: 'Catering',
      priceLabel: 'Price On Application',
      info: 'Catering for the wake or post-service gathering.',
    },
    {
      name: 'Newspaper Notice',
      priceLabel: 'Price On Application',
      info: 'Published death notice in local or national newspaper.',
    },
    {
      name: 'Saturday Service Fee',
      price: 880,
      info: 'Additional fee for services held on a Saturday.',
    },
  ],
};

const termsText =
  '* This package includes a funeral service at a chapel or a church with a funeral procession following to the crematorium. It includes many of the most commonly selected funeral options preselected for you. Many people choose this package for the extended funeral rituals — of course, you can tailor the funeral service to meet your needs and budget as you go through the selections.';

const packages = [
  {
    id: 'everyday',
    name: 'Everyday Funeral Package',
    price: 900,
    description:
      'Our most popular package with all essential services included. Suitable for a traditional chapel or church service.',
  },
  {
    id: 'deluxe',
    name: 'Deluxe Funeral Package',
    price: 1200,
    description: 'An enhanced package with premium coffin and additional floral arrangements.',
  },
  {
    id: 'essential',
    name: 'Essential Funeral Package',
    price: 600,
    description: 'A simple, dignified service covering all necessary arrangements.',
  },
  {
    id: 'catholic',
    name: 'Catholic Service',
    price: 950,
    description:
      'A service tailored for Catholic traditions including prayers and church ceremony.',
  },
];

const funeralTypes = ['All', 'Cremation', 'Burial', 'Memorial', 'Catholic', 'Direct Cremation'];

const FALogoNav = () => (
  <Box component="img" src="/brandlogo/logo-full.svg" alt="Funeral Arranger" sx={{ height: 28 }} />
);

const meta: Meta<typeof PackageDetail> = {
  title: 'Organisms/PackageDetail',
  component: PackageDetail,
  tags: ['autodocs'],
  parameters: {
    layout: 'centered',
  },
  decorators: [
    (Story) => (
      <Box sx={{ maxWidth: 600, width: '100%' }}>
        <Story />
      </Box>
    ),
  ],
};

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

// --- Default -----------------------------------------------------------------

/** Full package detail panel — Essentials, Optionals, Total, then Extras */
export const Default: Story = {
  args: {
    name: 'Traditional Family Cremation Service',
    price: 6966,
    sections: [
      { heading: 'Essentials', items: essentials },
      { heading: 'Optionals', items: optionals },
    ],
    total: 6966,
    extras,
    terms: termsText,
    onArrange: () => alert('Make Arrangement clicked'),
    onCompare: () => alert('Compare clicked'),
  },
};

// --- Compare Loading ---------------------------------------------------------

/** Compare button in loading state — adding to comparison cart */
export const CompareLoading: Story = {
  args: {
    name: 'Traditional Family Cremation Service',
    price: 6966,
    sections: [{ heading: 'Essentials', items: essentials.slice(0, 4) }],
    total: 6966,
    onArrange: () => alert('Make Arrangement'),
    onCompare: () => {},
    compareLoading: true,
  },
};

// --- Without Extras ----------------------------------------------------------

/** Simpler package with essentials and optionals only — no extras */
export const WithoutExtras: Story = {
  args: {
    name: 'Essential Cremation Package',
    price: 4850,
    sections: [
      { heading: 'Essentials', items: essentials.slice(0, 6) },
      { heading: 'Optionals', items: optionals.slice(0, 2) },
    ],
    total: 4850,
    terms: termsText,
    onArrange: () => alert('Make Arrangement'),
    onCompare: () => alert('Compare'),
  },
};

// --- Package Select Page Layout ----------------------------------------------

/** Full page layout — left: package list, right: detail panel */
export const PackageSelectPage: Story = {
  decorators: [
    (Story) => (
      <Box sx={{ maxWidth: 'none', width: '100%' }}>
        <Story />
      </Box>
    ),
  ],
  render: () => {
    const [selectedPkg, setSelectedPkg] = useState('everyday');
    const [activeFilter, setActiveFilter] = useState('Cremation');
    const [comparing, setComparing] = useState(false);

    const handleCompare = () => {
      setComparing(true);
      setTimeout(() => setComparing(false), 1500);
    };

    return (
      <Box>
        <Navigation
          logo={<FALogoNav />}
          items={[
            { label: 'Provider Portal', href: '/provider-portal' },
            { label: 'FAQ', href: '/faq' },
            { label: 'Contact Us', href: '/contact' },
            { label: 'Log in', href: '/login' },
          ]}
        />

        <Box
          sx={{
            display: 'grid',
            gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' },
            gap: { xs: 3, md: 4 },
            maxWidth: 'lg',
            mx: 'auto',
            px: { xs: 2, md: 4 },
            py: { xs: 2, md: 4 },
            alignItems: 'start',
          }}
        >
          {/* Left column */}
          <Box>
            <Button
              variant="text"
              color="secondary"
              startIcon={<ArrowBackIcon />}
              sx={{ mb: 2, ml: -1 }}
            >
              Back
            </Button>

            <Typography variant="h2" sx={{ mb: 3 }}>
              Select a package
            </Typography>

            <ProviderCardCompact
              name="H.Parsons"
              location="Wentworth"
              imageUrl={DEMO_IMAGE}
              rating={4.5}
              reviewCount={11}
              sx={{ mb: 3 }}
            />

            {/* Funeral type filter */}
            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, mb: 3 }}>
              {funeralTypes.map((type) => (
                <Chip
                  key={type}
                  label={type}
                  variant={activeFilter === type ? 'filled' : 'outlined'}
                  selected={activeFilter === type}
                  onClick={() => setActiveFilter(type)}
                  size="small"
                />
              ))}
            </Box>

            <Typography variant="h4" sx={{ mb: 2 }}>
              Packages
            </Typography>

            <Box
              role="radiogroup"
              aria-label="Available packages"
              sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}
            >
              {packages.map((pkg) => (
                <ServiceOption
                  key={pkg.id}
                  name={pkg.name}
                  price={pkg.price}
                  description={pkg.description}
                  selected={selectedPkg === pkg.id}
                  onClick={() => setSelectedPkg(pkg.id)}
                  maxDescriptionLines={2}
                />
              ))}
            </Box>
          </Box>

          {/* Right column: package detail */}
          <Box sx={{ position: { md: 'sticky' }, top: { md: 96 } }}>
            <PackageDetail
              name={packages.find((p) => p.id === selectedPkg)?.name ?? ''}
              price={packages.find((p) => p.id === selectedPkg)?.price ?? 0}
              sections={[
                { heading: 'Essentials', items: essentials },
                { heading: 'Optionals', items: optionals },
              ]}
              total={6966}
              extras={extras}
              terms={termsText}
              onArrange={() => alert(`Making arrangement for: ${selectedPkg}`)}
              onCompare={handleCompare}
              compareLoading={comparing}
            />
          </Box>
        </Box>
      </Box>
    );
  },
};
