import { DatePicker, Select, Switch, Input, Typography, theme, Button, Tooltip } from 'antd';
import {
  CalendarOutlined,
  UserOutlined,
  TagsOutlined,
  FolderOutlined,
  FileTextOutlined,
  EyeInvisibleOutlined,
  LinkOutlined,
  TeamOutlined,
  LeftOutlined,
  RightOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import type { BlogFrontmatter } from '@/hooks/useBlogFrontmatter';
import type { AuthorEntry } from '@/hooks/useBlogAuthors';

interface BlogFrontmatterPanelProps {
  frontmatter: BlogFrontmatter | null;
  onUpdate: (field: string, value: unknown) => void;
  authors: Record<string, AuthorEntry>;
  categories: string[];
  loading: boolean;
  collapsed: boolean;
  onCollapsedChange: (collapsed: boolean) => void;
  onManageAuthors: () => void;
}

const PANEL_WIDTH = 250;

export function BlogFrontmatterPanel({
  frontmatter,
  onUpdate,
  authors,
  categories,
  loading,
  collapsed,
  onCollapsedChange,
  onManageAuthors,
}: BlogFrontmatterPanelProps) {
  const { token } = theme.useToken();

  if (!frontmatter) return null;

  const authorOptions = Object.entries(authors || {}).map(([key, entry]) => ({
    label: entry.name,
    value: key,
  }));

  const categoryOptions = (categories || []).map((cat) => ({
    label: cat,
    value: cat,
  }));

  if (collapsed) {
    return (
      <div
        style={{
          width: 32,
          flexShrink: 0,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          paddingTop: 8,
          borderLeft: `1px solid ${token.colorBorderSecondary}`,
          background: token.colorBgContainer,
        }}
      >
        <Tooltip title="Show blog panel" placement="left">
          <Button
            type="text"
            size="small"
            icon={<LeftOutlined />}
            onClick={() => onCollapsedChange(false)}
          />
        </Tooltip>
      </div>
    );
  }

  return (
    <div
      style={{
        width: PANEL_WIDTH,
        flexShrink: 0,
        borderLeft: `1px solid ${token.colorBorderSecondary}`,
        background: token.colorBgContainer,
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden',
      }}
    >
      {/* Header */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '8px 12px',
          borderBottom: `1px solid ${token.colorBorderSecondary}`,
        }}
      >
        <Typography.Text strong style={{ fontSize: 13 }}>
          Blog
        </Typography.Text>
        <Tooltip title="Collapse panel">
          <Button
            type="text"
            size="small"
            icon={<RightOutlined />}
            onClick={() => onCollapsedChange(true)}
          />
        </Tooltip>
      </div>

      {/* Fields */}
      <div
        style={{
          flex: 1,
          overflow: 'auto',
          padding: '12px',
          display: 'flex',
          flexDirection: 'column',
          gap: 14,
        }}
      >
        {/* Date */}
        <FieldGroup icon={<CalendarOutlined />} label="Date">
          <DatePicker
            value={frontmatter.date ? dayjs(frontmatter.date) : undefined}
            onChange={(d) => onUpdate('date', d ? d.format('YYYY-MM-DD') : undefined)}
            format="YYYY-MM-DD"
            size="small"
            style={{ width: '100%' }}
            allowClear
          />
        </FieldGroup>

        {/* Authors */}
        <FieldGroup
          icon={<UserOutlined />}
          label="Authors"
          extra={
            <Tooltip title="Manage authors">
              <Button
                type="link"
                size="small"
                icon={<TeamOutlined />}
                onClick={onManageAuthors}
                style={{ padding: 0, height: 'auto', fontSize: 11 }}
              />
            </Tooltip>
          }
        >
          <Select
            mode="multiple"
            size="small"
            placeholder="Select authors"
            value={frontmatter.authors ?? []}
            onChange={(val) => onUpdate('authors', val)}
            options={authorOptions}
            loading={loading}
            style={{ width: '100%' }}
            maxTagCount="responsive"
          />
        </FieldGroup>

        {/* Categories */}
        <FieldGroup icon={<FolderOutlined />} label="Categories">
          <Select
            mode="tags"
            size="small"
            placeholder="Add categories"
            value={frontmatter.categories ?? []}
            onChange={(val) => onUpdate('categories', val)}
            options={categoryOptions}
            style={{ width: '100%' }}
            maxTagCount="responsive"
          />
        </FieldGroup>

        {/* Tags */}
        <FieldGroup icon={<TagsOutlined />} label="Tags">
          <Select
            mode="tags"
            size="small"
            placeholder="Add tags"
            value={frontmatter.tags ?? []}
            onChange={(val) => onUpdate('tags', val)}
            style={{ width: '100%' }}
            maxTagCount="responsive"
          />
        </FieldGroup>

        {/* Draft */}
        <FieldGroup icon={<EyeInvisibleOutlined />} label="Draft">
          <Switch
            size="small"
            checked={frontmatter.draft ?? false}
            onChange={(checked) => onUpdate('draft', checked || undefined)}
          />
        </FieldGroup>

        {/* Slug */}
        <FieldGroup icon={<LinkOutlined />} label="Slug">
          <Input
            size="small"
            placeholder="auto-generated"
            value={frontmatter.slug ?? ''}
            onChange={(e) => onUpdate('slug', e.target.value || undefined)}
            allowClear
          />
        </FieldGroup>

        {/* Description */}
        <FieldGroup icon={<FileTextOutlined />} label="Description">
          <Input.TextArea
            size="small"
            rows={3}
            placeholder="Post description / excerpt"
            value={frontmatter.description ?? ''}
            onChange={(e) => onUpdate('description', e.target.value || undefined)}
          />
        </FieldGroup>
      </div>
    </div>
  );
}

/** Small labeled field wrapper */
function FieldGroup({
  icon,
  label,
  extra,
  children,
}: {
  icon: React.ReactNode;
  label: string;
  extra?: React.ReactNode;
  children: React.ReactNode;
}) {
  const { token } = theme.useToken();

  return (
    <div>
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 4,
          marginBottom: 4,
        }}
      >
        <span style={{ color: token.colorTextSecondary, fontSize: 12 }}>{icon}</span>
        <Typography.Text
          style={{ fontSize: 11, fontWeight: 600, color: token.colorTextSecondary, textTransform: 'uppercase', letterSpacing: 0.3 }}
        >
          {label}
        </Typography.Text>
        {extra && <span style={{ marginLeft: 'auto' }}>{extra}</span>}
      </div>
      {children}
    </div>
  );
}
